diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c278fb1603a24c170727a492221b3e8ff2e9aafc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SessionServiceAsyncClient +from .client import SessionServiceClient + +__all__ = ( + "SessionServiceClient", + "SessionServiceAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1a745dab831325a562cc728b2ee7ef876eaa15 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/async_client.py @@ -0,0 +1,1079 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.session_service import pagers +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +from .client import SessionServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SessionServiceTransport +from .transports.grpc_asyncio import SessionServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SessionServiceAsyncClient: + """Service for managing Sessions and Session-related resources.""" + + _client: SessionServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SessionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SessionServiceClient._DEFAULT_UNIVERSE + + answer_path = staticmethod(SessionServiceClient.answer_path) + parse_answer_path = staticmethod(SessionServiceClient.parse_answer_path) + chunk_path = staticmethod(SessionServiceClient.chunk_path) + parse_chunk_path = staticmethod(SessionServiceClient.parse_chunk_path) + data_store_path = staticmethod(SessionServiceClient.data_store_path) + parse_data_store_path = staticmethod(SessionServiceClient.parse_data_store_path) + document_path = staticmethod(SessionServiceClient.document_path) + parse_document_path = staticmethod(SessionServiceClient.parse_document_path) + session_path = staticmethod(SessionServiceClient.session_path) + parse_session_path = staticmethod(SessionServiceClient.parse_session_path) + common_billing_account_path = staticmethod( + SessionServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SessionServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SessionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SessionServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SessionServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SessionServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SessionServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SessionServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SessionServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SessionServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceAsyncClient: The constructed client. + """ + return SessionServiceClient.from_service_account_info.__func__(SessionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceAsyncClient: The constructed client. + """ + return SessionServiceClient.from_service_account_file.__func__(SessionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SessionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SessionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SessionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = SessionServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SessionServiceTransport, Callable[..., SessionServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SessionServiceTransport,Callable[..., SessionServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SessionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SessionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1beta.SessionServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "credentialsType": None, + }, + ) + + async def create_session( + self, + request: Optional[ + Union[conversational_search_service.CreateSessionRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + session: Optional[gcd_session.Session] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_session.Session: + r"""Creates a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_create_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateSessionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSessionRequest, dict]]): + The request object. Request for CreateSession method. + parent (:class:`str`): + Required. Full resource name of parent data store. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session (:class:`google.cloud.discoveryengine_v1beta.types.Session`): + Required. The session to create. + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.Session: + External session proto definition. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, session] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.CreateSessionRequest): + request = conversational_search_service.CreateSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session is not None: + request.session = session + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_session( + self, + request: Optional[ + Union[conversational_search_service.DeleteSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_delete_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSessionRequest( + name="name_value", + ) + + # Make the request + await client.delete_session(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSessionRequest, dict]]): + The request object. Request for DeleteSession method. + name (:class:`str`): + Required. The resource name of the Session to delete. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.DeleteSessionRequest): + request = conversational_search_service.DeleteSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_session( + self, + request: Optional[ + Union[conversational_search_service.UpdateSessionRequest, dict] + ] = None, + *, + session: Optional[gcd_session.Session] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_session.Session: + r"""Updates a Session. + + [Session][google.cloud.discoveryengine.v1beta.Session] action + type cannot be changed. If the + [Session][google.cloud.discoveryengine.v1beta.Session] to update + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_update_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateSessionRequest( + ) + + # Make the request + response = await client.update_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateSessionRequest, dict]]): + The request object. Request for UpdateSession method. + session (:class:`google.cloud.discoveryengine_v1beta.types.Session`): + Required. The Session to update. + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which fields in the provided + [Session][google.cloud.discoveryengine.v1beta.Session] + to update. The following are NOT supported: + + - [Session.name][google.cloud.discoveryengine.v1beta.Session.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.Session: + External session proto definition. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [session, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.UpdateSessionRequest): + request = conversational_search_service.UpdateSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session is not None: + request.session = session + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("session.name", request.session.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_session( + self, + request: Optional[ + Union[conversational_search_service.GetSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session.Session: + r"""Gets a Session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_get_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSessionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetSessionRequest, dict]]): + The request object. Request for GetSession method. + name (:class:`str`): + Required. The resource name of the Session to get. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.Session: + External session proto definition. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.GetSessionRequest): + request = conversational_search_service.GetSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sessions( + self, + request: Optional[ + Union[conversational_search_service.ListSessionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSessionsAsyncPager: + r"""Lists all Sessions by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_list_sessions(): + # Create a client + client = discoveryengine_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sessions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListSessionsRequest, dict]]): + The request object. Request for ListSessions method. + parent (:class:`str`): + Required. The data store resource name. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.services.session_service.pagers.ListSessionsAsyncPager: + Response for ListSessions method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.ListSessionsRequest): + request = conversational_search_service.ListSessionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sessions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSessionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SessionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SessionServiceAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..73766d386aeb3c9d737089fa69b843aa069b64ed --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/client.py @@ -0,0 +1,1597 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.session_service import pagers +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +from .transports.base import DEFAULT_CLIENT_INFO, SessionServiceTransport +from .transports.grpc import SessionServiceGrpcTransport +from .transports.grpc_asyncio import SessionServiceGrpcAsyncIOTransport +from .transports.rest import SessionServiceRestTransport + + +class SessionServiceClientMeta(type): + """Metaclass for the SessionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[SessionServiceTransport]] + _transport_registry["grpc"] = SessionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SessionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SessionServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SessionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SessionServiceClient(metaclass=SessionServiceClientMeta): + """Service for managing Sessions and Session-related resources.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SessionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def answer_path( + project: str, + location: str, + data_store: str, + session: str, + answer: str, + ) -> str: + """Returns a fully-qualified answer string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}/answers/{answer}".format( + project=project, + location=location, + data_store=data_store, + session=session, + answer=answer, + ) + + @staticmethod + def parse_answer_path(path: str) -> Dict[str, str]: + """Parses a answer path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/sessions/(?P.+?)/answers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def chunk_path( + project: str, + location: str, + data_store: str, + branch: str, + document: str, + chunk: str, + ) -> str: + """Returns a fully-qualified chunk string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}/chunks/{chunk}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + chunk=chunk, + ) + + @staticmethod + def parse_chunk_path(path: str) -> Dict[str, str]: + """Parses a chunk path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)/chunks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def data_store_path( + project: str, + location: str, + data_store: str, + ) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format( + project=project, + location=location, + data_store=data_store, + ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str, str]: + """Parses a data_store path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def document_path( + project: str, + location: str, + data_store: str, + branch: str, + document: str, + ) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str, str]: + """Parses a document path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def session_path( + project: str, + location: str, + data_store: str, + session: str, + ) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format( + project=project, + location=location, + data_store=data_store, + session=session, + ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str, str]: + """Parses a session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/sessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SessionServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SessionServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SessionServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SessionServiceTransport, Callable[..., SessionServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SessionServiceTransport,Callable[..., SessionServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SessionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SessionServiceClient._read_environment_variables() + self._client_cert_source = SessionServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SessionServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SessionServiceTransport) + if transport_provided: + # transport is a SessionServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SessionServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SessionServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SessionServiceTransport], Callable[..., SessionServiceTransport] + ] = ( + SessionServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SessionServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1beta.SessionServiceClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "credentialsType": None, + }, + ) + + def create_session( + self, + request: Optional[ + Union[conversational_search_service.CreateSessionRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + session: Optional[gcd_session.Session] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_session.Session: + r"""Creates a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_create_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateSessionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateSessionRequest, dict]): + The request object. Request for CreateSession method. + parent (str): + Required. Full resource name of parent data store. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session (google.cloud.discoveryengine_v1beta.types.Session): + Required. The session to create. + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.Session: + External session proto definition. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, session] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.CreateSessionRequest): + request = conversational_search_service.CreateSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session is not None: + request.session = session + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_session( + self, + request: Optional[ + Union[conversational_search_service.DeleteSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_delete_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSessionRequest( + name="name_value", + ) + + # Make the request + client.delete_session(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSessionRequest, dict]): + The request object. Request for DeleteSession method. + name (str): + Required. The resource name of the Session to delete. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.DeleteSessionRequest): + request = conversational_search_service.DeleteSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_session( + self, + request: Optional[ + Union[conversational_search_service.UpdateSessionRequest, dict] + ] = None, + *, + session: Optional[gcd_session.Session] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_session.Session: + r"""Updates a Session. + + [Session][google.cloud.discoveryengine.v1beta.Session] action + type cannot be changed. If the + [Session][google.cloud.discoveryengine.v1beta.Session] to update + does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_update_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateSessionRequest( + ) + + # Make the request + response = client.update_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateSessionRequest, dict]): + The request object. Request for UpdateSession method. + session (google.cloud.discoveryengine_v1beta.types.Session): + Required. The Session to update. + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Session][google.cloud.discoveryengine.v1beta.Session] + to update. The following are NOT supported: + + - [Session.name][google.cloud.discoveryengine.v1beta.Session.name] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.Session: + External session proto definition. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [session, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.UpdateSessionRequest): + request = conversational_search_service.UpdateSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session is not None: + request.session = session + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("session.name", request.session.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_session( + self, + request: Optional[ + Union[conversational_search_service.GetSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session.Session: + r"""Gets a Session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_get_session(): + # Create a client + client = discoveryengine_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetSessionRequest, dict]): + The request object. Request for GetSession method. + name (str): + Required. The resource name of the Session to get. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.Session: + External session proto definition. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.GetSessionRequest): + request = conversational_search_service.GetSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sessions( + self, + request: Optional[ + Union[conversational_search_service.ListSessionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSessionsPager: + r"""Lists all Sessions by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_list_sessions(): + # Create a client + client = discoveryengine_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sessions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListSessionsRequest, dict]): + The request object. Request for ListSessions method. + parent (str): + Required. The data store resource name. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.services.session_service.pagers.ListSessionsPager: + Response for ListSessions method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversational_search_service.ListSessionsRequest): + request = conversational_search_service.ListSessionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_sessions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSessionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SessionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SessionServiceClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..519fa65bf54ded70bacc4630601a0fd161abe973 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/pagers.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + conversational_search_service, + session, +) + + +class ListSessionsPager: + """A pager for iterating through ``list_sessions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSessionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sessions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSessions`` requests and continue to iterate + through the ``sessions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSessionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., conversational_search_service.ListSessionsResponse], + request: conversational_search_service.ListSessionsRequest, + response: conversational_search_service.ListSessionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListSessionsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSessionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = conversational_search_service.ListSessionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversational_search_service.ListSessionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[session.Session]: + for page in self.pages: + yield from page.sessions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSessionsAsyncPager: + """A pager for iterating through ``list_sessions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSessionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sessions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSessions`` requests and continue to iterate + through the ``sessions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSessionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[conversational_search_service.ListSessionsResponse] + ], + request: conversational_search_service.ListSessionsRequest, + response: conversational_search_service.ListSessionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListSessionsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSessionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = conversational_search_service.ListSessionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[conversational_search_service.ListSessionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[session.Session]: + async def async_generator(): + async for page in self.pages: + for response in page.sessions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d258a984225b33d842c8ba3384389984867ca3a4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionServiceTransport +from .grpc import SessionServiceGrpcTransport +from .grpc_asyncio import SessionServiceGrpcAsyncIOTransport +from .rest import SessionServiceRestInterceptor, SessionServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionServiceTransport]] +_transport_registry["grpc"] = SessionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SessionServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SessionServiceRestTransport + +__all__ = ( + "SessionServiceTransport", + "SessionServiceGrpcTransport", + "SessionServiceGrpcAsyncIOTransport", + "SessionServiceRestTransport", + "SessionServiceRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a11bf35f7b185d943c5be78482011c007f2c6c05 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/base.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SessionServiceTransport(abc.ABC): + """Abstract transport class for SessionService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "discoveryengine.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_session: gapic_v1.method.wrap_method( + self.create_session, + default_timeout=None, + client_info=client_info, + ), + self.delete_session: gapic_v1.method.wrap_method( + self.delete_session, + default_timeout=None, + client_info=client_info, + ), + self.update_session: gapic_v1.method.wrap_method( + self.update_session, + default_timeout=None, + client_info=client_info, + ), + self.get_session: gapic_v1.method.wrap_method( + self.get_session, + default_timeout=None, + client_info=client_info, + ), + self.list_sessions: gapic_v1.method.wrap_method( + self.list_sessions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_session( + self, + ) -> Callable[ + [conversational_search_service.CreateSessionRequest], + Union[gcd_session.Session, Awaitable[gcd_session.Session]], + ]: + raise NotImplementedError() + + @property + def delete_session( + self, + ) -> Callable[ + [conversational_search_service.DeleteSessionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def update_session( + self, + ) -> Callable[ + [conversational_search_service.UpdateSessionRequest], + Union[gcd_session.Session, Awaitable[gcd_session.Session]], + ]: + raise NotImplementedError() + + @property + def get_session( + self, + ) -> Callable[ + [conversational_search_service.GetSessionRequest], + Union[session.Session, Awaitable[session.Session]], + ]: + raise NotImplementedError() + + @property + def list_sessions( + self, + ) -> Callable[ + [conversational_search_service.ListSessionsRequest], + Union[ + conversational_search_service.ListSessionsResponse, + Awaitable[conversational_search_service.ListSessionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SessionServiceTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd4297625026d18a9b368730e8a2a8bee1707a6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/grpc.py @@ -0,0 +1,539 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +from .base import DEFAULT_CLIENT_INFO, SessionServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SessionServiceGrpcTransport(SessionServiceTransport): + """gRPC backend transport for SessionService. + + Service for managing Sessions and Session-related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_session( + self, + ) -> Callable[ + [conversational_search_service.CreateSessionRequest], gcd_session.Session + ]: + r"""Return a callable for the create session method over gRPC. + + Creates a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateSessionRequest], + ~.Session]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_session" not in self._stubs: + self._stubs["create_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/CreateSession", + request_serializer=conversational_search_service.CreateSessionRequest.serialize, + response_deserializer=gcd_session.Session.deserialize, + ) + return self._stubs["create_session"] + + @property + def delete_session( + self, + ) -> Callable[ + [conversational_search_service.DeleteSessionRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete session method over gRPC. + + Deletes a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteSessionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_session" not in self._stubs: + self._stubs["delete_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/DeleteSession", + request_serializer=conversational_search_service.DeleteSessionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_session"] + + @property + def update_session( + self, + ) -> Callable[ + [conversational_search_service.UpdateSessionRequest], gcd_session.Session + ]: + r"""Return a callable for the update session method over gRPC. + + Updates a Session. + + [Session][google.cloud.discoveryengine.v1beta.Session] action + type cannot be changed. If the + [Session][google.cloud.discoveryengine.v1beta.Session] to update + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateSessionRequest], + ~.Session]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_session" not in self._stubs: + self._stubs["update_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/UpdateSession", + request_serializer=conversational_search_service.UpdateSessionRequest.serialize, + response_deserializer=gcd_session.Session.deserialize, + ) + return self._stubs["update_session"] + + @property + def get_session( + self, + ) -> Callable[[conversational_search_service.GetSessionRequest], session.Session]: + r"""Return a callable for the get session method over gRPC. + + Gets a Session. + + Returns: + Callable[[~.GetSessionRequest], + ~.Session]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_session" not in self._stubs: + self._stubs["get_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/GetSession", + request_serializer=conversational_search_service.GetSessionRequest.serialize, + response_deserializer=session.Session.deserialize, + ) + return self._stubs["get_session"] + + @property + def list_sessions( + self, + ) -> Callable[ + [conversational_search_service.ListSessionsRequest], + conversational_search_service.ListSessionsResponse, + ]: + r"""Return a callable for the list sessions method over gRPC. + + Lists all Sessions by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.ListSessionsRequest], + ~.ListSessionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_sessions" not in self._stubs: + self._stubs["list_sessions"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/ListSessions", + request_serializer=conversational_search_service.ListSessionsRequest.serialize, + response_deserializer=conversational_search_service.ListSessionsResponse.deserialize, + ) + return self._stubs["list_sessions"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SessionServiceGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..75ddf9af70faa3e0e99d7a5bc71f4e801db534e0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/grpc_asyncio.py @@ -0,0 +1,601 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +from .base import DEFAULT_CLIENT_INFO, SessionServiceTransport +from .grpc import SessionServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SessionServiceGrpcAsyncIOTransport(SessionServiceTransport): + """gRPC AsyncIO backend transport for SessionService. + + Service for managing Sessions and Session-related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_session( + self, + ) -> Callable[ + [conversational_search_service.CreateSessionRequest], + Awaitable[gcd_session.Session], + ]: + r"""Return a callable for the create session method over gRPC. + + Creates a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateSessionRequest], + Awaitable[~.Session]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_session" not in self._stubs: + self._stubs["create_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/CreateSession", + request_serializer=conversational_search_service.CreateSessionRequest.serialize, + response_deserializer=gcd_session.Session.deserialize, + ) + return self._stubs["create_session"] + + @property + def delete_session( + self, + ) -> Callable[ + [conversational_search_service.DeleteSessionRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete session method over gRPC. + + Deletes a Session. + + If the [Session][google.cloud.discoveryengine.v1beta.Session] to + delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteSessionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_session" not in self._stubs: + self._stubs["delete_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/DeleteSession", + request_serializer=conversational_search_service.DeleteSessionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_session"] + + @property + def update_session( + self, + ) -> Callable[ + [conversational_search_service.UpdateSessionRequest], + Awaitable[gcd_session.Session], + ]: + r"""Return a callable for the update session method over gRPC. + + Updates a Session. + + [Session][google.cloud.discoveryengine.v1beta.Session] action + type cannot be changed. If the + [Session][google.cloud.discoveryengine.v1beta.Session] to update + does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.UpdateSessionRequest], + Awaitable[~.Session]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_session" not in self._stubs: + self._stubs["update_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/UpdateSession", + request_serializer=conversational_search_service.UpdateSessionRequest.serialize, + response_deserializer=gcd_session.Session.deserialize, + ) + return self._stubs["update_session"] + + @property + def get_session( + self, + ) -> Callable[ + [conversational_search_service.GetSessionRequest], Awaitable[session.Session] + ]: + r"""Return a callable for the get session method over gRPC. + + Gets a Session. + + Returns: + Callable[[~.GetSessionRequest], + Awaitable[~.Session]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_session" not in self._stubs: + self._stubs["get_session"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/GetSession", + request_serializer=conversational_search_service.GetSessionRequest.serialize, + response_deserializer=session.Session.deserialize, + ) + return self._stubs["get_session"] + + @property + def list_sessions( + self, + ) -> Callable[ + [conversational_search_service.ListSessionsRequest], + Awaitable[conversational_search_service.ListSessionsResponse], + ]: + r"""Return a callable for the list sessions method over gRPC. + + Lists all Sessions by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.ListSessionsRequest], + Awaitable[~.ListSessionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_sessions" not in self._stubs: + self._stubs["list_sessions"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SessionService/ListSessions", + request_serializer=conversational_search_service.ListSessionsRequest.serialize, + response_deserializer=conversational_search_service.ListSessionsResponse.deserialize, + ) + return self._stubs["list_sessions"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_session: self._wrap_method( + self.create_session, + default_timeout=None, + client_info=client_info, + ), + self.delete_session: self._wrap_method( + self.delete_session, + default_timeout=None, + client_info=client_info, + ), + self.update_session: self._wrap_method( + self.update_session, + default_timeout=None, + client_info=client_info, + ), + self.get_session: self._wrap_method( + self.get_session, + default_timeout=None, + client_info=client_info, + ), + self.list_sessions: self._wrap_method( + self.list_sessions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SessionServiceGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8606d71ad1423e150686b3bddce1ce767bf027 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/rest.py @@ -0,0 +1,1647 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSessionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SessionServiceRestInterceptor: + """Interceptor for SessionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SessionServiceRestTransport. + + .. code-block:: python + class MyCustomSessionServiceInterceptor(SessionServiceRestInterceptor): + def pre_create_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_session(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_session(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sessions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sessions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_session(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SessionServiceRestTransport(interceptor=MyCustomSessionServiceInterceptor()) + client = SessionServiceClient(transport=transport) + + + """ + + def pre_create_session( + self, + request: conversational_search_service.CreateSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversational_search_service.CreateSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_create_session(self, response: gcd_session.Session) -> gcd_session.Session: + """Post-rpc interceptor for create_session + + DEPRECATED. Please use the `post_create_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_create_session` interceptor runs + before the `post_create_session_with_metadata` interceptor. + """ + return response + + def post_create_session_with_metadata( + self, + response: gcd_session.Session, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcd_session.Session, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_create_session_with_metadata` + interceptor in new development instead of the `post_create_session` interceptor. + When both interceptors are used, this `post_create_session_with_metadata` interceptor runs after the + `post_create_session` interceptor. The (possibly modified) response returned by + `post_create_session` will be passed to + `post_create_session_with_metadata`. + """ + return response, metadata + + def pre_delete_session( + self, + request: conversational_search_service.DeleteSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversational_search_service.DeleteSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def pre_get_session( + self, + request: conversational_search_service.GetSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversational_search_service.GetSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_get_session(self, response: session.Session) -> session.Session: + """Post-rpc interceptor for get_session + + DEPRECATED. Please use the `post_get_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_get_session` interceptor runs + before the `post_get_session_with_metadata` interceptor. + """ + return response + + def post_get_session_with_metadata( + self, + response: session.Session, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[session.Session, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_get_session_with_metadata` + interceptor in new development instead of the `post_get_session` interceptor. + When both interceptors are used, this `post_get_session_with_metadata` interceptor runs after the + `post_get_session` interceptor. The (possibly modified) response returned by + `post_get_session` will be passed to + `post_get_session_with_metadata`. + """ + return response, metadata + + def pre_list_sessions( + self, + request: conversational_search_service.ListSessionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversational_search_service.ListSessionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_sessions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_list_sessions( + self, response: conversational_search_service.ListSessionsResponse + ) -> conversational_search_service.ListSessionsResponse: + """Post-rpc interceptor for list_sessions + + DEPRECATED. Please use the `post_list_sessions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_list_sessions` interceptor runs + before the `post_list_sessions_with_metadata` interceptor. + """ + return response + + def post_list_sessions_with_metadata( + self, + response: conversational_search_service.ListSessionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversational_search_service.ListSessionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_sessions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_list_sessions_with_metadata` + interceptor in new development instead of the `post_list_sessions` interceptor. + When both interceptors are used, this `post_list_sessions_with_metadata` interceptor runs after the + `post_list_sessions` interceptor. The (possibly modified) response returned by + `post_list_sessions` will be passed to + `post_list_sessions_with_metadata`. + """ + return response, metadata + + def pre_update_session( + self, + request: conversational_search_service.UpdateSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversational_search_service.UpdateSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_update_session(self, response: gcd_session.Session) -> gcd_session.Session: + """Post-rpc interceptor for update_session + + DEPRECATED. Please use the `post_update_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_update_session` interceptor runs + before the `post_update_session_with_metadata` interceptor. + """ + return response + + def post_update_session_with_metadata( + self, + response: gcd_session.Session, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcd_session.Session, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_update_session_with_metadata` + interceptor in new development instead of the `post_update_session` interceptor. + When both interceptors are used, this `post_update_session_with_metadata` interceptor runs after the + `post_update_session` interceptor. The (possibly modified) response returned by + `post_update_session` will be passed to + `post_update_session_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SessionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SessionServiceRestInterceptor + + +class SessionServiceRestTransport(_BaseSessionServiceRestTransport): + """REST backend synchronous transport for SessionService. + + Service for managing Sessions and Session-related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SessionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SessionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateSession( + _BaseSessionServiceRestTransport._BaseCreateSession, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.CreateSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: conversational_search_service.CreateSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_session.Session: + r"""Call the create session method over HTTP. + + Args: + request (~.conversational_search_service.CreateSessionRequest): + The request object. Request for CreateSession method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcd_session.Session: + External session proto definition. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseCreateSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_session(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseCreateSession._get_transcoded_request( + http_options, request + ) + + body = _BaseSessionServiceRestTransport._BaseCreateSession._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseCreateSession._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.CreateSession", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "CreateSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._CreateSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_session.Session() + pb_resp = gcd_session.Session.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcd_session.Session.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SessionServiceClient.create_session", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "CreateSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSession( + _BaseSessionServiceRestTransport._BaseDeleteSession, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.DeleteSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: conversational_search_service.DeleteSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete session method over HTTP. + + Args: + request (~.conversational_search_service.DeleteSessionRequest): + The request object. Request for DeleteSession method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseDeleteSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_session(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseDeleteSession._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseDeleteSession._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.DeleteSession", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "DeleteSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._DeleteSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetSession( + _BaseSessionServiceRestTransport._BaseGetSession, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.GetSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: conversational_search_service.GetSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session.Session: + r"""Call the get session method over HTTP. + + Args: + request (~.conversational_search_service.GetSessionRequest): + The request object. Request for GetSession method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.session.Session: + External session proto definition. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseGetSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_session(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseGetSession._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseSessionServiceRestTransport._BaseGetSession._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.GetSession", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "GetSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._GetSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = session.Session() + pb_resp = session.Session.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = session.Session.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SessionServiceClient.get_session", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "GetSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSessions( + _BaseSessionServiceRestTransport._BaseListSessions, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.ListSessions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: conversational_search_service.ListSessionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversational_search_service.ListSessionsResponse: + r"""Call the list sessions method over HTTP. + + Args: + request (~.conversational_search_service.ListSessionsRequest): + The request object. Request for ListSessions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversational_search_service.ListSessionsResponse: + Response for ListSessions method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseListSessions._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_sessions(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseListSessions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseListSessions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.ListSessions", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "ListSessions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._ListSessions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ListSessionsResponse() + pb_resp = conversational_search_service.ListSessionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sessions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sessions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + conversational_search_service.ListSessionsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SessionServiceClient.list_sessions", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "ListSessions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSession( + _BaseSessionServiceRestTransport._BaseUpdateSession, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.UpdateSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: conversational_search_service.UpdateSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_session.Session: + r"""Call the update session method over HTTP. + + Args: + request (~.conversational_search_service.UpdateSessionRequest): + The request object. Request for UpdateSession method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcd_session.Session: + External session proto definition. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseUpdateSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_session(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseUpdateSession._get_transcoded_request( + http_options, request + ) + + body = _BaseSessionServiceRestTransport._BaseUpdateSession._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseUpdateSession._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.UpdateSession", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "UpdateSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._UpdateSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_session.Session() + pb_resp = gcd_session.Session.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcd_session.Session.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SessionServiceClient.update_session", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "UpdateSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_session( + self, + ) -> Callable[ + [conversational_search_service.CreateSessionRequest], gcd_session.Session + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_session( + self, + ) -> Callable[ + [conversational_search_service.DeleteSessionRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_session( + self, + ) -> Callable[[conversational_search_service.GetSessionRequest], session.Session]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sessions( + self, + ) -> Callable[ + [conversational_search_service.ListSessionsRequest], + conversational_search_service.ListSessionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSessions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_session( + self, + ) -> Callable[ + [conversational_search_service.UpdateSessionRequest], gcd_session.Session + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseSessionServiceRestTransport._BaseCancelOperation, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseSessionServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseSessionServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseSessionServiceRestTransport._BaseGetOperation, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SessionServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseSessionServiceRestTransport._BaseListOperations, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SessionServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SessionServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SessionService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SessionServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4da0f0a14e8f878daa0609d00680d4f3a81535ff --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/session_service/transports/rest_base.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import session +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +from .base import DEFAULT_CLIENT_INFO, SessionServiceTransport + + +class _BaseSessionServiceRestTransport(SessionServiceTransport): + """Base REST backend transport for SessionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*}/sessions", + "body": "session", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/sessions", + "body": "session", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/engines/*}/sessions", + "body": "session", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversational_search_service.CreateSessionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSessionServiceRestTransport._BaseCreateSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/sessions/*}", + }, + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/sessions/*}", + }, + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/sessions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversational_search_service.DeleteSessionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSessionServiceRestTransport._BaseDeleteSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/sessions/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/sessions/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/sessions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversational_search_service.GetSessionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSessionServiceRestTransport._BaseGetSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSessions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*}/sessions", + }, + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/sessions", + }, + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/engines/*}/sessions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversational_search_service.ListSessionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSessionServiceRestTransport._BaseListSessions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{session.name=projects/*/locations/*/dataStores/*/sessions/*}", + "body": "session", + }, + { + "method": "patch", + "uri": "/v1beta/{session.name=projects/*/locations/*/collections/*/dataStores/*/sessions/*}", + "body": "session", + }, + { + "method": "patch", + "uri": "/v1beta/{session.name=projects/*/locations/*/collections/*/engines/*/sessions/*}", + "body": "session", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversational_search_service.UpdateSessionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSessionServiceRestTransport._BaseUpdateSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSessionServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8039b8753159cd4873b7abbe47f4e6f3469c1c26 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SiteSearchEngineServiceAsyncClient +from .client import SiteSearchEngineServiceClient + +__all__ = ( + "SiteSearchEngineServiceClient", + "SiteSearchEngineServiceAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..89b86b5877ec02736a5069fdf58d843479600e57 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py @@ -0,0 +1,2404 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.site_search_engine_service import ( + pagers, +) +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +from .client import SiteSearchEngineServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SiteSearchEngineServiceTransport +from .transports.grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SiteSearchEngineServiceAsyncClient: + """Service for managing site search related resources.""" + + _client: SiteSearchEngineServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SiteSearchEngineServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SiteSearchEngineServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + SiteSearchEngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = SiteSearchEngineServiceClient._DEFAULT_UNIVERSE + + sitemap_path = staticmethod(SiteSearchEngineServiceClient.sitemap_path) + parse_sitemap_path = staticmethod(SiteSearchEngineServiceClient.parse_sitemap_path) + site_search_engine_path = staticmethod( + SiteSearchEngineServiceClient.site_search_engine_path + ) + parse_site_search_engine_path = staticmethod( + SiteSearchEngineServiceClient.parse_site_search_engine_path + ) + target_site_path = staticmethod(SiteSearchEngineServiceClient.target_site_path) + parse_target_site_path = staticmethod( + SiteSearchEngineServiceClient.parse_target_site_path + ) + common_billing_account_path = staticmethod( + SiteSearchEngineServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SiteSearchEngineServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SiteSearchEngineServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SiteSearchEngineServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SiteSearchEngineServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SiteSearchEngineServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + SiteSearchEngineServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + SiteSearchEngineServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + SiteSearchEngineServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SiteSearchEngineServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SiteSearchEngineServiceAsyncClient: The constructed client. + """ + return SiteSearchEngineServiceClient.from_service_account_info.__func__(SiteSearchEngineServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SiteSearchEngineServiceAsyncClient: The constructed client. + """ + return SiteSearchEngineServiceClient.from_service_account_file.__func__(SiteSearchEngineServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SiteSearchEngineServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SiteSearchEngineServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SiteSearchEngineServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = SiteSearchEngineServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SiteSearchEngineServiceTransport, + Callable[..., SiteSearchEngineServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the site search engine service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SiteSearchEngineServiceTransport,Callable[..., SiteSearchEngineServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SiteSearchEngineServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SiteSearchEngineServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "credentialsType": None, + }, + ) + + async def get_site_search_engine( + self, + request: Optional[ + Union[site_search_engine_service.GetSiteSearchEngineRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine.SiteSearchEngine: + r"""Gets the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_get_site_search_engine(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSiteSearchEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_site_search_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetSiteSearchEngineRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.GetSiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetSiteSearchEngine] + method. + name (:class:`str`): + Required. Resource name of + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + If the caller does not have permission to access the + [SiteSearchEngine], regardless of whether or not it + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.SiteSearchEngine: + SiteSearchEngine captures DataStore + level site search persisting + configurations. It is a singleton value + per data store. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.GetSiteSearchEngineRequest + ): + request = site_search_engine_service.GetSiteSearchEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_site_search_engine + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_target_site( + self, + request: Optional[ + Union[site_search_engine_service.CreateTargetSiteRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + target_site: Optional[site_search_engine.TargetSite] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_create_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + target_site = discoveryengine_v1beta.TargetSite() + target_site.provided_uri_pattern = "provided_uri_pattern_value" + + request = discoveryengine_v1beta.CreateTargetSiteRequest( + parent="parent_value", + target_site=target_site, + ) + + # Make the request + operation = client.create_target_site(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.CreateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite] + method. + parent (:class:`str`): + Required. Parent resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_site (:class:`google.cloud.discoveryengine_v1beta.types.TargetSite`): + Required. The + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + to create. + + This corresponds to the ``target_site`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.TargetSite` + A target site for the SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, target_site] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.CreateTargetSiteRequest): + request = site_search_engine_service.CreateTargetSiteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if target_site is not None: + request.target_site = target_site + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_target_site + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine.TargetSite, + metadata_type=site_search_engine_service.CreateTargetSiteMetadata, + ) + + # Done; return the response. + return response + + async def batch_create_target_sites( + self, + request: Optional[ + Union[site_search_engine_service.BatchCreateTargetSitesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] in + a batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_batch_create_target_sites(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + requests = discoveryengine_v1beta.CreateTargetSiteRequest() + requests.parent = "parent_value" + requests.target_site.provided_uri_pattern = "provided_uri_pattern_value" + + request = discoveryengine_v1beta.BatchCreateTargetSitesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_target_sites(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesResponse` Response message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.BatchCreateTargetSitesRequest + ): + request = site_search_engine_service.BatchCreateTargetSitesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_create_target_sites + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine_service.BatchCreateTargetSitesResponse, + metadata_type=site_search_engine_service.BatchCreateTargetSiteMetadata, + ) + + # Done; return the response. + return response + + async def get_target_site( + self, + request: Optional[ + Union[site_search_engine_service.GetTargetSiteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine.TargetSite: + r"""Gets a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_get_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetTargetSiteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_target_site(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetTargetSiteRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.GetTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetTargetSite] + method. + name (:class:`str`): + Required. Full resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}``. + + If the caller does not have permission to access the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.TargetSite: + A target site for the + SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.GetTargetSiteRequest): + request = site_search_engine_service.GetTargetSiteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_target_site + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_target_site( + self, + request: Optional[ + Union[site_search_engine_service.UpdateTargetSiteRequest, dict] + ] = None, + *, + target_site: Optional[site_search_engine.TargetSite] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_update_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + target_site = discoveryengine_v1beta.TargetSite() + target_site.provided_uri_pattern = "provided_uri_pattern_value" + + request = discoveryengine_v1beta.UpdateTargetSiteRequest( + target_site=target_site, + ) + + # Make the request + operation = client.update_target_site(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateTargetSiteRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.UpdateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.UpdateTargetSite] + method. + target_site (:class:`google.cloud.discoveryengine_v1beta.types.TargetSite`): + Required. The target site to update. If the caller does + not have permission to update the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``target_site`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.TargetSite` + A target site for the SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [target_site] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.UpdateTargetSiteRequest): + request = site_search_engine_service.UpdateTargetSiteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if target_site is not None: + request.target_site = target_site + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_target_site + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("target_site.name", request.target_site.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine.TargetSite, + metadata_type=site_search_engine_service.UpdateTargetSiteMetadata, + ) + + # Done; return the response. + return response + + async def delete_target_site( + self, + request: Optional[ + Union[site_search_engine_service.DeleteTargetSiteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_delete_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteTargetSiteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_target_site(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteTargetSiteRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.DeleteTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteTargetSite] + method. + name (:class:`str`): + Required. Full resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}``. + + If the caller does not have permission to access the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.DeleteTargetSiteRequest): + request = site_search_engine_service.DeleteTargetSiteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_target_site + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=site_search_engine_service.DeleteTargetSiteMetadata, + ) + + # Done; return the response. + return response + + async def list_target_sites( + self, + request: Optional[ + Union[site_search_engine_service.ListTargetSitesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTargetSitesAsyncPager: + r"""Gets a list of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_list_target_sites(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListTargetSitesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_target_sites(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListTargetSitesRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + parent (:class:`str`): + Required. The parent site search engine resource name, + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + If the caller does not have permission to list + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s + under this site search engine, regardless of whether or + not this branch exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.services.site_search_engine_service.pagers.ListTargetSitesAsyncPager: + Response message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.ListTargetSitesRequest): + request = site_search_engine_service.ListTargetSitesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_target_sites + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTargetSitesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.CreateSitemapRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sitemap: Optional[site_search_engine.Sitemap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_create_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + sitemap = discoveryengine_v1beta.Sitemap() + sitemap.uri = "uri_value" + + request = discoveryengine_v1beta.CreateSitemapRequest( + parent="parent_value", + sitemap=sitemap, + ) + + # Make the request + operation = client.create_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSitemapRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + parent (:class:`str`): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sitemap (:class:`google.cloud.discoveryengine_v1beta.types.Sitemap`): + Required. The + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + to create. + + This corresponds to the ``sitemap`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Sitemap` + A sitemap for the SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, sitemap] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.CreateSitemapRequest): + request = site_search_engine_service.CreateSitemapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sitemap is not None: + request.sitemap = sitemap + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sitemap + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine.Sitemap, + metadata_type=site_search_engine_service.CreateSitemapMetadata, + ) + + # Done; return the response. + return response + + async def delete_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.DeleteSitemapRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_delete_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSitemapRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSitemapRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + name (:class:`str`): + Required. Full resource name of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}``. + + If the caller does not have permission to access the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.DeleteSitemapRequest): + request = site_search_engine_service.DeleteSitemapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sitemap + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=site_search_engine_service.DeleteSitemapMetadata, + ) + + # Done; return the response. + return response + + async def fetch_sitemaps( + self, + request: Optional[ + Union[site_search_engine_service.FetchSitemapsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine_service.FetchSitemapsResponse: + r"""Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_fetch_sitemaps(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchSitemapsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_sitemaps(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + parent (:class:`str`): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse: + Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.FetchSitemapsRequest): + request = site_search_engine_service.FetchSitemapsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_sitemaps + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def enable_advanced_site_search( + self, + request: Optional[ + Union[site_search_engine_service.EnableAdvancedSiteSearchRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Upgrade from basic site search to advanced site + search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_enable_advanced_site_search(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.EnableAdvancedSiteSearchRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.enable_advanced_site_search(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.EnableAdvancedSiteSearchRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.EnableAdvancedSiteSearchResponse` Response message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.EnableAdvancedSiteSearchRequest + ): + request = site_search_engine_service.EnableAdvancedSiteSearchRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.enable_advanced_site_search + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine_service.EnableAdvancedSiteSearchResponse, + metadata_type=site_search_engine_service.EnableAdvancedSiteSearchMetadata, + ) + + # Done; return the response. + return response + + async def disable_advanced_site_search( + self, + request: Optional[ + Union[site_search_engine_service.DisableAdvancedSiteSearchRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Downgrade from advanced site search to basic site + search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_disable_advanced_site_search(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DisableAdvancedSiteSearchRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.disable_advanced_site_search(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DisableAdvancedSiteSearchRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.DisableAdvancedSiteSearchResponse` Response message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.DisableAdvancedSiteSearchRequest + ): + request = site_search_engine_service.DisableAdvancedSiteSearchRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.disable_advanced_site_search + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine_service.DisableAdvancedSiteSearchResponse, + metadata_type=site_search_engine_service.DisableAdvancedSiteSearchMetadata, + ) + + # Done; return the response. + return response + + async def recrawl_uris( + self, + request: Optional[ + Union[site_search_engine_service.RecrawlUrisRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Request on-demand recrawl for a list of URIs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_recrawl_uris(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + uris=['uris_value1', 'uris_value2'], + ) + + # Make the request + operation = client.recrawl_uris(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.RecrawlUrisRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.RecrawlUrisResponse` Response message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.RecrawlUrisRequest): + request = site_search_engine_service.RecrawlUrisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.recrawl_uris + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine_service.RecrawlUrisResponse, + metadata_type=site_search_engine_service.RecrawlUrisMetadata, + ) + + # Done; return the response. + return response + + async def batch_verify_target_sites( + self, + request: Optional[ + Union[site_search_engine_service.BatchVerifyTargetSitesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Verify target sites' ownership and validity. + This API sends all the target sites under site search + engine for verification. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_batch_verify_target_sites(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.BatchVerifyTargetSitesRequest( + parent="parent_value", + ) + + # Make the request + operation = client.batch_verify_target_sites(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesResponse` Response message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.BatchVerifyTargetSitesRequest + ): + request = site_search_engine_service.BatchVerifyTargetSitesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_verify_target_sites + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine_service.BatchVerifyTargetSitesResponse, + metadata_type=site_search_engine_service.BatchVerifyTargetSitesMetadata, + ) + + # Done; return the response. + return response + + async def fetch_domain_verification_status( + self, + request: Optional[ + Union[site_search_engine_service.FetchDomainVerificationStatusRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchDomainVerificationStatusAsyncPager: + r"""Returns list of target sites with its domain verification + status. This method can only be called under data store with + BASIC_SITE_SEARCH state at the moment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_fetch_domain_verification_status(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchDomainVerificationStatusRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + page_result = client.fetch_domain_verification_status(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.services.site_search_engine_service.pagers.FetchDomainVerificationStatusAsyncPager: + Response message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.FetchDomainVerificationStatusRequest + ): + request = site_search_engine_service.FetchDomainVerificationStatusRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_domain_verification_status + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchDomainVerificationStatusAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SiteSearchEngineServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SiteSearchEngineServiceAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..e79f570058da7ca4910d801063416f8ee0c9e53c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py @@ -0,0 +1,2849 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.site_search_engine_service import ( + pagers, +) +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +from .transports.base import DEFAULT_CLIENT_INFO, SiteSearchEngineServiceTransport +from .transports.grpc import SiteSearchEngineServiceGrpcTransport +from .transports.grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport +from .transports.rest import SiteSearchEngineServiceRestTransport + + +class SiteSearchEngineServiceClientMeta(type): + """Metaclass for the SiteSearchEngineService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[SiteSearchEngineServiceTransport]] + _transport_registry["grpc"] = SiteSearchEngineServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SiteSearchEngineServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SiteSearchEngineServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SiteSearchEngineServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SiteSearchEngineServiceClient(metaclass=SiteSearchEngineServiceClientMeta): + """Service for managing site search related resources.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SiteSearchEngineServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SiteSearchEngineServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SiteSearchEngineServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SiteSearchEngineServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def sitemap_path( + project: str, + location: str, + data_store: str, + sitemap: str, + ) -> str: + """Returns a fully-qualified sitemap string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}".format( + project=project, + location=location, + data_store=data_store, + sitemap=sitemap, + ) + + @staticmethod + def parse_sitemap_path(path: str) -> Dict[str, str]: + """Parses a sitemap path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/siteSearchEngine/sitemaps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def site_search_engine_path( + project: str, + location: str, + data_store: str, + ) -> str: + """Returns a fully-qualified site_search_engine string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine".format( + project=project, + location=location, + data_store=data_store, + ) + + @staticmethod + def parse_site_search_engine_path(path: str) -> Dict[str, str]: + """Parses a site_search_engine path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/siteSearchEngine$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def target_site_path( + project: str, + location: str, + data_store: str, + target_site: str, + ) -> str: + """Returns a fully-qualified target_site string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}".format( + project=project, + location=location, + data_store=data_store, + target_site=target_site, + ) + + @staticmethod + def parse_target_site_path(path: str) -> Dict[str, str]: + """Parses a target_site path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/siteSearchEngine/targetSites/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SiteSearchEngineServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SiteSearchEngineServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + SiteSearchEngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SiteSearchEngineServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SiteSearchEngineServiceTransport, + Callable[..., SiteSearchEngineServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the site search engine service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SiteSearchEngineServiceTransport,Callable[..., SiteSearchEngineServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SiteSearchEngineServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SiteSearchEngineServiceClient._read_environment_variables() + self._client_cert_source = ( + SiteSearchEngineServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = SiteSearchEngineServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SiteSearchEngineServiceTransport) + if transport_provided: + # transport is a SiteSearchEngineServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SiteSearchEngineServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SiteSearchEngineServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SiteSearchEngineServiceTransport], + Callable[..., SiteSearchEngineServiceTransport], + ] = ( + SiteSearchEngineServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SiteSearchEngineServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "credentialsType": None, + }, + ) + + def get_site_search_engine( + self, + request: Optional[ + Union[site_search_engine_service.GetSiteSearchEngineRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine.SiteSearchEngine: + r"""Gets the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_get_site_search_engine(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSiteSearchEngineRequest( + name="name_value", + ) + + # Make the request + response = client.get_site_search_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetSiteSearchEngineRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.GetSiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetSiteSearchEngine] + method. + name (str): + Required. Resource name of + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + If the caller does not have permission to access the + [SiteSearchEngine], regardless of whether or not it + exists, a PERMISSION_DENIED error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.SiteSearchEngine: + SiteSearchEngine captures DataStore + level site search persisting + configurations. It is a singleton value + per data store. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.GetSiteSearchEngineRequest + ): + request = site_search_engine_service.GetSiteSearchEngineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_site_search_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_target_site( + self, + request: Optional[ + Union[site_search_engine_service.CreateTargetSiteRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + target_site: Optional[site_search_engine.TargetSite] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_create_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + target_site = discoveryengine_v1beta.TargetSite() + target_site.provided_uri_pattern = "provided_uri_pattern_value" + + request = discoveryengine_v1beta.CreateTargetSiteRequest( + parent="parent_value", + target_site=target_site, + ) + + # Make the request + operation = client.create_target_site(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.CreateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite] + method. + parent (str): + Required. Parent resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_site (google.cloud.discoveryengine_v1beta.types.TargetSite): + Required. The + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + to create. + + This corresponds to the ``target_site`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.TargetSite` + A target site for the SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, target_site] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.CreateTargetSiteRequest): + request = site_search_engine_service.CreateTargetSiteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if target_site is not None: + request.target_site = target_site + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_target_site] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine.TargetSite, + metadata_type=site_search_engine_service.CreateTargetSiteMetadata, + ) + + # Done; return the response. + return response + + def batch_create_target_sites( + self, + request: Optional[ + Union[site_search_engine_service.BatchCreateTargetSitesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] in + a batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_batch_create_target_sites(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + requests = discoveryengine_v1beta.CreateTargetSiteRequest() + requests.parent = "parent_value" + requests.target_site.provided_uri_pattern = "provided_uri_pattern_value" + + request = discoveryengine_v1beta.BatchCreateTargetSitesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_target_sites(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesResponse` Response message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.BatchCreateTargetSitesRequest + ): + request = site_search_engine_service.BatchCreateTargetSitesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_create_target_sites + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine_service.BatchCreateTargetSitesResponse, + metadata_type=site_search_engine_service.BatchCreateTargetSiteMetadata, + ) + + # Done; return the response. + return response + + def get_target_site( + self, + request: Optional[ + Union[site_search_engine_service.GetTargetSiteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine.TargetSite: + r"""Gets a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_get_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetTargetSiteRequest( + name="name_value", + ) + + # Make the request + response = client.get_target_site(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetTargetSiteRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.GetTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetTargetSite] + method. + name (str): + Required. Full resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}``. + + If the caller does not have permission to access the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.TargetSite: + A target site for the + SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.GetTargetSiteRequest): + request = site_search_engine_service.GetTargetSiteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_target_site] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_target_site( + self, + request: Optional[ + Union[site_search_engine_service.UpdateTargetSiteRequest, dict] + ] = None, + *, + target_site: Optional[site_search_engine.TargetSite] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_update_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + target_site = discoveryengine_v1beta.TargetSite() + target_site.provided_uri_pattern = "provided_uri_pattern_value" + + request = discoveryengine_v1beta.UpdateTargetSiteRequest( + target_site=target_site, + ) + + # Make the request + operation = client.update_target_site(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateTargetSiteRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.UpdateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.UpdateTargetSite] + method. + target_site (google.cloud.discoveryengine_v1beta.types.TargetSite): + Required. The target site to update. If the caller does + not have permission to update the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``target_site`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.TargetSite` + A target site for the SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [target_site] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.UpdateTargetSiteRequest): + request = site_search_engine_service.UpdateTargetSiteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if target_site is not None: + request.target_site = target_site + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_target_site] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("target_site.name", request.target_site.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine.TargetSite, + metadata_type=site_search_engine_service.UpdateTargetSiteMetadata, + ) + + # Done; return the response. + return response + + def delete_target_site( + self, + request: Optional[ + Union[site_search_engine_service.DeleteTargetSiteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_delete_target_site(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteTargetSiteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_target_site(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteTargetSiteRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.DeleteTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteTargetSite] + method. + name (str): + Required. Full resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}``. + + If the caller does not have permission to access the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.DeleteTargetSiteRequest): + request = site_search_engine_service.DeleteTargetSiteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_target_site] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=site_search_engine_service.DeleteTargetSiteMetadata, + ) + + # Done; return the response. + return response + + def list_target_sites( + self, + request: Optional[ + Union[site_search_engine_service.ListTargetSitesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTargetSitesPager: + r"""Gets a list of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_list_target_sites(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListTargetSitesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_target_sites(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListTargetSitesRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + parent (str): + Required. The parent site search engine resource name, + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + If the caller does not have permission to list + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s + under this site search engine, regardless of whether or + not this branch exists, a PERMISSION_DENIED error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.services.site_search_engine_service.pagers.ListTargetSitesPager: + Response message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.ListTargetSitesRequest): + request = site_search_engine_service.ListTargetSitesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_target_sites] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTargetSitesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.CreateSitemapRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sitemap: Optional[site_search_engine.Sitemap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_create_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + sitemap = discoveryengine_v1beta.Sitemap() + sitemap.uri = "uri_value" + + request = discoveryengine_v1beta.CreateSitemapRequest( + parent="parent_value", + sitemap=sitemap, + ) + + # Make the request + operation = client.create_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateSitemapRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sitemap (google.cloud.discoveryengine_v1beta.types.Sitemap): + Required. The + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + to create. + + This corresponds to the ``sitemap`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Sitemap` + A sitemap for the SiteSearchEngine. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, sitemap] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.CreateSitemapRequest): + request = site_search_engine_service.CreateSitemapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sitemap is not None: + request.sitemap = sitemap + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sitemap] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine.Sitemap, + metadata_type=site_search_engine_service.CreateSitemapMetadata, + ) + + # Done; return the response. + return response + + def delete_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.DeleteSitemapRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_delete_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSitemapRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSitemapRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + name (str): + Required. Full resource name of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}``. + + If the caller does not have permission to access the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.DeleteSitemapRequest): + request = site_search_engine_service.DeleteSitemapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_sitemap] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=site_search_engine_service.DeleteSitemapMetadata, + ) + + # Done; return the response. + return response + + def fetch_sitemaps( + self, + request: Optional[ + Union[site_search_engine_service.FetchSitemapsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine_service.FetchSitemapsResponse: + r"""Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_fetch_sitemaps(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchSitemapsRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_sitemaps(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse: + Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.FetchSitemapsRequest): + request = site_search_engine_service.FetchSitemapsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_sitemaps] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def enable_advanced_site_search( + self, + request: Optional[ + Union[site_search_engine_service.EnableAdvancedSiteSearchRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Upgrade from basic site search to advanced site + search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_enable_advanced_site_search(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.EnableAdvancedSiteSearchRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.enable_advanced_site_search(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.EnableAdvancedSiteSearchRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.EnableAdvancedSiteSearchResponse` Response message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.EnableAdvancedSiteSearchRequest + ): + request = site_search_engine_service.EnableAdvancedSiteSearchRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.enable_advanced_site_search + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine_service.EnableAdvancedSiteSearchResponse, + metadata_type=site_search_engine_service.EnableAdvancedSiteSearchMetadata, + ) + + # Done; return the response. + return response + + def disable_advanced_site_search( + self, + request: Optional[ + Union[site_search_engine_service.DisableAdvancedSiteSearchRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Downgrade from advanced site search to basic site + search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_disable_advanced_site_search(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DisableAdvancedSiteSearchRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.disable_advanced_site_search(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DisableAdvancedSiteSearchRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.DisableAdvancedSiteSearchResponse` Response message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.DisableAdvancedSiteSearchRequest + ): + request = site_search_engine_service.DisableAdvancedSiteSearchRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.disable_advanced_site_search + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine_service.DisableAdvancedSiteSearchResponse, + metadata_type=site_search_engine_service.DisableAdvancedSiteSearchMetadata, + ) + + # Done; return the response. + return response + + def recrawl_uris( + self, + request: Optional[ + Union[site_search_engine_service.RecrawlUrisRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Request on-demand recrawl for a list of URIs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_recrawl_uris(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + uris=['uris_value1', 'uris_value2'], + ) + + # Make the request + operation = client.recrawl_uris(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.RecrawlUrisRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.RecrawlUrisResponse` Response message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, site_search_engine_service.RecrawlUrisRequest): + request = site_search_engine_service.RecrawlUrisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.recrawl_uris] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine_service.RecrawlUrisResponse, + metadata_type=site_search_engine_service.RecrawlUrisMetadata, + ) + + # Done; return the response. + return response + + def batch_verify_target_sites( + self, + request: Optional[ + Union[site_search_engine_service.BatchVerifyTargetSitesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Verify target sites' ownership and validity. + This API sends all the target sites under site search + engine for verification. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_batch_verify_target_sites(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.BatchVerifyTargetSitesRequest( + parent="parent_value", + ) + + # Make the request + operation = client.batch_verify_target_sites(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesResponse` Response message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.BatchVerifyTargetSitesRequest + ): + request = site_search_engine_service.BatchVerifyTargetSitesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_verify_target_sites + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine_service.BatchVerifyTargetSitesResponse, + metadata_type=site_search_engine_service.BatchVerifyTargetSitesMetadata, + ) + + # Done; return the response. + return response + + def fetch_domain_verification_status( + self, + request: Optional[ + Union[site_search_engine_service.FetchDomainVerificationStatusRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchDomainVerificationStatusPager: + r"""Returns list of target sites with its domain verification + status. This method can only be called under data store with + BASIC_SITE_SEARCH state at the moment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_fetch_domain_verification_status(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchDomainVerificationStatusRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + page_result = client.fetch_domain_verification_status(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.services.site_search_engine_service.pagers.FetchDomainVerificationStatusPager: + Response message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.FetchDomainVerificationStatusRequest + ): + request = site_search_engine_service.FetchDomainVerificationStatusRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_domain_verification_status + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchDomainVerificationStatusPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SiteSearchEngineServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SiteSearchEngineServiceClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..e9d54b6c0c8ffb817299da250b2e439078d319bf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/pagers.py @@ -0,0 +1,375 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + + +class ListTargetSitesPager: + """A pager for iterating through ``list_target_sites`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListTargetSitesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``target_sites`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTargetSites`` requests and continue to iterate + through the ``target_sites`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListTargetSitesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., site_search_engine_service.ListTargetSitesResponse], + request: site_search_engine_service.ListTargetSitesRequest, + response: site_search_engine_service.ListTargetSitesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListTargetSitesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListTargetSitesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = site_search_engine_service.ListTargetSitesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[site_search_engine_service.ListTargetSitesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[site_search_engine.TargetSite]: + for page in self.pages: + yield from page.target_sites + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTargetSitesAsyncPager: + """A pager for iterating through ``list_target_sites`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListTargetSitesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``target_sites`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTargetSites`` requests and continue to iterate + through the ``target_sites`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListTargetSitesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[site_search_engine_service.ListTargetSitesResponse] + ], + request: site_search_engine_service.ListTargetSitesRequest, + response: site_search_engine_service.ListTargetSitesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListTargetSitesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListTargetSitesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = site_search_engine_service.ListTargetSitesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[site_search_engine_service.ListTargetSitesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[site_search_engine.TargetSite]: + async def async_generator(): + async for page in self.pages: + for response in page.target_sites: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchDomainVerificationStatusPager: + """A pager for iterating through ``fetch_domain_verification_status`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusResponse` object, and + provides an ``__iter__`` method to iterate through its + ``target_sites`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchDomainVerificationStatus`` requests and continue to iterate + through the ``target_sites`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., site_search_engine_service.FetchDomainVerificationStatusResponse + ], + request: site_search_engine_service.FetchDomainVerificationStatusRequest, + response: site_search_engine_service.FetchDomainVerificationStatusResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = site_search_engine_service.FetchDomainVerificationStatusRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[site_search_engine_service.FetchDomainVerificationStatusResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[site_search_engine.TargetSite]: + for page in self.pages: + yield from page.target_sites + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchDomainVerificationStatusAsyncPager: + """A pager for iterating through ``fetch_domain_verification_status`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``target_sites`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchDomainVerificationStatus`` requests and continue to iterate + through the ``target_sites`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[site_search_engine_service.FetchDomainVerificationStatusResponse], + ], + request: site_search_engine_service.FetchDomainVerificationStatusRequest, + response: site_search_engine_service.FetchDomainVerificationStatusResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.FetchDomainVerificationStatusResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = site_search_engine_service.FetchDomainVerificationStatusRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + site_search_engine_service.FetchDomainVerificationStatusResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[site_search_engine.TargetSite]: + async def async_generator(): + async for page in self.pages: + for response in page.target_sites: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5443c0c10cf110a415abc4820d34991cb0cd0789 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SiteSearchEngineServiceTransport +from .grpc import SiteSearchEngineServiceGrpcTransport +from .grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport +from .rest import ( + SiteSearchEngineServiceRestInterceptor, + SiteSearchEngineServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SiteSearchEngineServiceTransport]] +_transport_registry["grpc"] = SiteSearchEngineServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SiteSearchEngineServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SiteSearchEngineServiceRestTransport + +__all__ = ( + "SiteSearchEngineServiceTransport", + "SiteSearchEngineServiceGrpcTransport", + "SiteSearchEngineServiceGrpcAsyncIOTransport", + "SiteSearchEngineServiceRestTransport", + "SiteSearchEngineServiceRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..620ad168227af28565b84d6ab2d44a204f1dbdc0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py @@ -0,0 +1,425 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SiteSearchEngineServiceTransport(abc.ABC): + """Abstract transport class for SiteSearchEngineService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "discoveryengine.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_site_search_engine: gapic_v1.method.wrap_method( + self.get_site_search_engine, + default_timeout=None, + client_info=client_info, + ), + self.create_target_site: gapic_v1.method.wrap_method( + self.create_target_site, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_target_sites: gapic_v1.method.wrap_method( + self.batch_create_target_sites, + default_timeout=None, + client_info=client_info, + ), + self.get_target_site: gapic_v1.method.wrap_method( + self.get_target_site, + default_timeout=None, + client_info=client_info, + ), + self.update_target_site: gapic_v1.method.wrap_method( + self.update_target_site, + default_timeout=None, + client_info=client_info, + ), + self.delete_target_site: gapic_v1.method.wrap_method( + self.delete_target_site, + default_timeout=None, + client_info=client_info, + ), + self.list_target_sites: gapic_v1.method.wrap_method( + self.list_target_sites, + default_timeout=None, + client_info=client_info, + ), + self.create_sitemap: gapic_v1.method.wrap_method( + self.create_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.delete_sitemap: gapic_v1.method.wrap_method( + self.delete_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.fetch_sitemaps: gapic_v1.method.wrap_method( + self.fetch_sitemaps, + default_timeout=None, + client_info=client_info, + ), + self.enable_advanced_site_search: gapic_v1.method.wrap_method( + self.enable_advanced_site_search, + default_timeout=None, + client_info=client_info, + ), + self.disable_advanced_site_search: gapic_v1.method.wrap_method( + self.disable_advanced_site_search, + default_timeout=None, + client_info=client_info, + ), + self.recrawl_uris: gapic_v1.method.wrap_method( + self.recrawl_uris, + default_timeout=None, + client_info=client_info, + ), + self.batch_verify_target_sites: gapic_v1.method.wrap_method( + self.batch_verify_target_sites, + default_timeout=None, + client_info=client_info, + ), + self.fetch_domain_verification_status: gapic_v1.method.wrap_method( + self.fetch_domain_verification_status, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_site_search_engine( + self, + ) -> Callable[ + [site_search_engine_service.GetSiteSearchEngineRequest], + Union[ + site_search_engine.SiteSearchEngine, + Awaitable[site_search_engine.SiteSearchEngine], + ], + ]: + raise NotImplementedError() + + @property + def create_target_site( + self, + ) -> Callable[ + [site_search_engine_service.CreateTargetSiteRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def batch_create_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchCreateTargetSitesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_target_site( + self, + ) -> Callable[ + [site_search_engine_service.GetTargetSiteRequest], + Union[site_search_engine.TargetSite, Awaitable[site_search_engine.TargetSite]], + ]: + raise NotImplementedError() + + @property + def update_target_site( + self, + ) -> Callable[ + [site_search_engine_service.UpdateTargetSiteRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_target_site( + self, + ) -> Callable[ + [site_search_engine_service.DeleteTargetSiteRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.ListTargetSitesRequest], + Union[ + site_search_engine_service.ListTargetSitesResponse, + Awaitable[site_search_engine_service.ListTargetSitesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + Union[ + site_search_engine_service.FetchSitemapsResponse, + Awaitable[site_search_engine_service.FetchSitemapsResponse], + ], + ]: + raise NotImplementedError() + + @property + def enable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.EnableAdvancedSiteSearchRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def disable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.DisableAdvancedSiteSearchRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def recrawl_uris( + self, + ) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def batch_verify_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchVerifyTargetSitesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def fetch_domain_verification_status( + self, + ) -> Callable[ + [site_search_engine_service.FetchDomainVerificationStatusRequest], + Union[ + site_search_engine_service.FetchDomainVerificationStatusResponse, + Awaitable[site_search_engine_service.FetchDomainVerificationStatusResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SiteSearchEngineServiceTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..fb63e7cfef3dfef29a50f46108e94e43e76542a3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py @@ -0,0 +1,857 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +from .base import DEFAULT_CLIENT_INFO, SiteSearchEngineServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SiteSearchEngineServiceGrpcTransport(SiteSearchEngineServiceTransport): + """gRPC backend transport for SiteSearchEngineService. + + Service for managing site search related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_site_search_engine( + self, + ) -> Callable[ + [site_search_engine_service.GetSiteSearchEngineRequest], + site_search_engine.SiteSearchEngine, + ]: + r"""Return a callable for the get site search engine method over gRPC. + + Gets the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine]. + + Returns: + Callable[[~.GetSiteSearchEngineRequest], + ~.SiteSearchEngine]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_site_search_engine" not in self._stubs: + self._stubs["get_site_search_engine"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/GetSiteSearchEngine", + request_serializer=site_search_engine_service.GetSiteSearchEngineRequest.serialize, + response_deserializer=site_search_engine.SiteSearchEngine.deserialize, + ) + return self._stubs["get_site_search_engine"] + + @property + def create_target_site( + self, + ) -> Callable[ + [site_search_engine_service.CreateTargetSiteRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create target site method over gRPC. + + Creates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.CreateTargetSiteRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_target_site" not in self._stubs: + self._stubs["create_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/CreateTargetSite", + request_serializer=site_search_engine_service.CreateTargetSiteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_target_site"] + + @property + def batch_create_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchCreateTargetSitesRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the batch create target sites method over gRPC. + + Creates + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] in + a batch. + + Returns: + Callable[[~.BatchCreateTargetSitesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_create_target_sites" not in self._stubs: + self._stubs["batch_create_target_sites"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/BatchCreateTargetSites", + request_serializer=site_search_engine_service.BatchCreateTargetSitesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_create_target_sites"] + + @property + def get_target_site( + self, + ) -> Callable[ + [site_search_engine_service.GetTargetSiteRequest], site_search_engine.TargetSite + ]: + r"""Return a callable for the get target site method over gRPC. + + Gets a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.GetTargetSiteRequest], + ~.TargetSite]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_target_site" not in self._stubs: + self._stubs["get_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/GetTargetSite", + request_serializer=site_search_engine_service.GetTargetSiteRequest.serialize, + response_deserializer=site_search_engine.TargetSite.deserialize, + ) + return self._stubs["get_target_site"] + + @property + def update_target_site( + self, + ) -> Callable[ + [site_search_engine_service.UpdateTargetSiteRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update target site method over gRPC. + + Updates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.UpdateTargetSiteRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_target_site" not in self._stubs: + self._stubs["update_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/UpdateTargetSite", + request_serializer=site_search_engine_service.UpdateTargetSiteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_target_site"] + + @property + def delete_target_site( + self, + ) -> Callable[ + [site_search_engine_service.DeleteTargetSiteRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete target site method over gRPC. + + Deletes a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.DeleteTargetSiteRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_target_site" not in self._stubs: + self._stubs["delete_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DeleteTargetSite", + request_serializer=site_search_engine_service.DeleteTargetSiteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_target_site"] + + @property + def list_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.ListTargetSitesRequest], + site_search_engine_service.ListTargetSitesResponse, + ]: + r"""Return a callable for the list target sites method over gRPC. + + Gets a list of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s. + + Returns: + Callable[[~.ListTargetSitesRequest], + ~.ListTargetSitesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_target_sites" not in self._stubs: + self._stubs["list_target_sites"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/ListTargetSites", + request_serializer=site_search_engine_service.ListTargetSitesRequest.serialize, + response_deserializer=site_search_engine_service.ListTargetSitesResponse.deserialize, + ) + return self._stubs["list_target_sites"] + + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create sitemap method over gRPC. + + Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.CreateSitemapRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_sitemap" not in self._stubs: + self._stubs["create_sitemap"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/CreateSitemap", + request_serializer=site_search_engine_service.CreateSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sitemap"] + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete sitemap method over gRPC. + + Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.DeleteSitemapRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sitemap" not in self._stubs: + self._stubs["delete_sitemap"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DeleteSitemap", + request_serializer=site_search_engine_service.DeleteSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sitemap"] + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + site_search_engine_service.FetchSitemapsResponse, + ]: + r"""Return a callable for the fetch sitemaps method over gRPC. + + Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.FetchSitemapsRequest], + ~.FetchSitemapsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_sitemaps" not in self._stubs: + self._stubs["fetch_sitemaps"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/FetchSitemaps", + request_serializer=site_search_engine_service.FetchSitemapsRequest.serialize, + response_deserializer=site_search_engine_service.FetchSitemapsResponse.deserialize, + ) + return self._stubs["fetch_sitemaps"] + + @property + def enable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.EnableAdvancedSiteSearchRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the enable advanced site search method over gRPC. + + Upgrade from basic site search to advanced site + search. + + Returns: + Callable[[~.EnableAdvancedSiteSearchRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_advanced_site_search" not in self._stubs: + self._stubs[ + "enable_advanced_site_search" + ] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/EnableAdvancedSiteSearch", + request_serializer=site_search_engine_service.EnableAdvancedSiteSearchRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["enable_advanced_site_search"] + + @property + def disable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.DisableAdvancedSiteSearchRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the disable advanced site search method over gRPC. + + Downgrade from advanced site search to basic site + search. + + Returns: + Callable[[~.DisableAdvancedSiteSearchRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_advanced_site_search" not in self._stubs: + self._stubs[ + "disable_advanced_site_search" + ] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DisableAdvancedSiteSearch", + request_serializer=site_search_engine_service.DisableAdvancedSiteSearchRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["disable_advanced_site_search"] + + @property + def recrawl_uris( + self, + ) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], operations_pb2.Operation + ]: + r"""Return a callable for the recrawl uris method over gRPC. + + Request on-demand recrawl for a list of URIs. + + Returns: + Callable[[~.RecrawlUrisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "recrawl_uris" not in self._stubs: + self._stubs["recrawl_uris"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/RecrawlUris", + request_serializer=site_search_engine_service.RecrawlUrisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["recrawl_uris"] + + @property + def batch_verify_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchVerifyTargetSitesRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the batch verify target sites method over gRPC. + + Verify target sites' ownership and validity. + This API sends all the target sites under site search + engine for verification. + + Returns: + Callable[[~.BatchVerifyTargetSitesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_verify_target_sites" not in self._stubs: + self._stubs["batch_verify_target_sites"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/BatchVerifyTargetSites", + request_serializer=site_search_engine_service.BatchVerifyTargetSitesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_verify_target_sites"] + + @property + def fetch_domain_verification_status( + self, + ) -> Callable[ + [site_search_engine_service.FetchDomainVerificationStatusRequest], + site_search_engine_service.FetchDomainVerificationStatusResponse, + ]: + r"""Return a callable for the fetch domain verification + status method over gRPC. + + Returns list of target sites with its domain verification + status. This method can only be called under data store with + BASIC_SITE_SEARCH state at the moment. + + Returns: + Callable[[~.FetchDomainVerificationStatusRequest], + ~.FetchDomainVerificationStatusResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_domain_verification_status" not in self._stubs: + self._stubs[ + "fetch_domain_verification_status" + ] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/FetchDomainVerificationStatus", + request_serializer=site_search_engine_service.FetchDomainVerificationStatusRequest.serialize, + response_deserializer=site_search_engine_service.FetchDomainVerificationStatusResponse.deserialize, + ) + return self._stubs["fetch_domain_verification_status"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SiteSearchEngineServiceGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..3348c80310ab11af0036c18d89069f511f293a90 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py @@ -0,0 +1,972 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +from .base import DEFAULT_CLIENT_INFO, SiteSearchEngineServiceTransport +from .grpc import SiteSearchEngineServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SiteSearchEngineServiceGrpcAsyncIOTransport(SiteSearchEngineServiceTransport): + """gRPC AsyncIO backend transport for SiteSearchEngineService. + + Service for managing site search related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_site_search_engine( + self, + ) -> Callable[ + [site_search_engine_service.GetSiteSearchEngineRequest], + Awaitable[site_search_engine.SiteSearchEngine], + ]: + r"""Return a callable for the get site search engine method over gRPC. + + Gets the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine]. + + Returns: + Callable[[~.GetSiteSearchEngineRequest], + Awaitable[~.SiteSearchEngine]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_site_search_engine" not in self._stubs: + self._stubs["get_site_search_engine"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/GetSiteSearchEngine", + request_serializer=site_search_engine_service.GetSiteSearchEngineRequest.serialize, + response_deserializer=site_search_engine.SiteSearchEngine.deserialize, + ) + return self._stubs["get_site_search_engine"] + + @property + def create_target_site( + self, + ) -> Callable[ + [site_search_engine_service.CreateTargetSiteRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create target site method over gRPC. + + Creates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.CreateTargetSiteRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_target_site" not in self._stubs: + self._stubs["create_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/CreateTargetSite", + request_serializer=site_search_engine_service.CreateTargetSiteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_target_site"] + + @property + def batch_create_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchCreateTargetSitesRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the batch create target sites method over gRPC. + + Creates + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] in + a batch. + + Returns: + Callable[[~.BatchCreateTargetSitesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_create_target_sites" not in self._stubs: + self._stubs["batch_create_target_sites"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/BatchCreateTargetSites", + request_serializer=site_search_engine_service.BatchCreateTargetSitesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_create_target_sites"] + + @property + def get_target_site( + self, + ) -> Callable[ + [site_search_engine_service.GetTargetSiteRequest], + Awaitable[site_search_engine.TargetSite], + ]: + r"""Return a callable for the get target site method over gRPC. + + Gets a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.GetTargetSiteRequest], + Awaitable[~.TargetSite]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_target_site" not in self._stubs: + self._stubs["get_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/GetTargetSite", + request_serializer=site_search_engine_service.GetTargetSiteRequest.serialize, + response_deserializer=site_search_engine.TargetSite.deserialize, + ) + return self._stubs["get_target_site"] + + @property + def update_target_site( + self, + ) -> Callable[ + [site_search_engine_service.UpdateTargetSiteRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update target site method over gRPC. + + Updates a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.UpdateTargetSiteRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_target_site" not in self._stubs: + self._stubs["update_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/UpdateTargetSite", + request_serializer=site_search_engine_service.UpdateTargetSiteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_target_site"] + + @property + def delete_target_site( + self, + ) -> Callable[ + [site_search_engine_service.DeleteTargetSiteRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete target site method over gRPC. + + Deletes a + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + + Returns: + Callable[[~.DeleteTargetSiteRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_target_site" not in self._stubs: + self._stubs["delete_target_site"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DeleteTargetSite", + request_serializer=site_search_engine_service.DeleteTargetSiteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_target_site"] + + @property + def list_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.ListTargetSitesRequest], + Awaitable[site_search_engine_service.ListTargetSitesResponse], + ]: + r"""Return a callable for the list target sites method over gRPC. + + Gets a list of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s. + + Returns: + Callable[[~.ListTargetSitesRequest], + Awaitable[~.ListTargetSitesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_target_sites" not in self._stubs: + self._stubs["list_target_sites"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/ListTargetSites", + request_serializer=site_search_engine_service.ListTargetSitesRequest.serialize, + response_deserializer=site_search_engine_service.ListTargetSitesResponse.deserialize, + ) + return self._stubs["list_target_sites"] + + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create sitemap method over gRPC. + + Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.CreateSitemapRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_sitemap" not in self._stubs: + self._stubs["create_sitemap"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/CreateSitemap", + request_serializer=site_search_engine_service.CreateSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sitemap"] + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete sitemap method over gRPC. + + Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.DeleteSitemapRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sitemap" not in self._stubs: + self._stubs["delete_sitemap"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DeleteSitemap", + request_serializer=site_search_engine_service.DeleteSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sitemap"] + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + Awaitable[site_search_engine_service.FetchSitemapsResponse], + ]: + r"""Return a callable for the fetch sitemaps method over gRPC. + + Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.FetchSitemapsRequest], + Awaitable[~.FetchSitemapsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_sitemaps" not in self._stubs: + self._stubs["fetch_sitemaps"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/FetchSitemaps", + request_serializer=site_search_engine_service.FetchSitemapsRequest.serialize, + response_deserializer=site_search_engine_service.FetchSitemapsResponse.deserialize, + ) + return self._stubs["fetch_sitemaps"] + + @property + def enable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.EnableAdvancedSiteSearchRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the enable advanced site search method over gRPC. + + Upgrade from basic site search to advanced site + search. + + Returns: + Callable[[~.EnableAdvancedSiteSearchRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_advanced_site_search" not in self._stubs: + self._stubs[ + "enable_advanced_site_search" + ] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/EnableAdvancedSiteSearch", + request_serializer=site_search_engine_service.EnableAdvancedSiteSearchRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["enable_advanced_site_search"] + + @property + def disable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.DisableAdvancedSiteSearchRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the disable advanced site search method over gRPC. + + Downgrade from advanced site search to basic site + search. + + Returns: + Callable[[~.DisableAdvancedSiteSearchRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_advanced_site_search" not in self._stubs: + self._stubs[ + "disable_advanced_site_search" + ] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DisableAdvancedSiteSearch", + request_serializer=site_search_engine_service.DisableAdvancedSiteSearchRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["disable_advanced_site_search"] + + @property + def recrawl_uris( + self, + ) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the recrawl uris method over gRPC. + + Request on-demand recrawl for a list of URIs. + + Returns: + Callable[[~.RecrawlUrisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "recrawl_uris" not in self._stubs: + self._stubs["recrawl_uris"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/RecrawlUris", + request_serializer=site_search_engine_service.RecrawlUrisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["recrawl_uris"] + + @property + def batch_verify_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchVerifyTargetSitesRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the batch verify target sites method over gRPC. + + Verify target sites' ownership and validity. + This API sends all the target sites under site search + engine for verification. + + Returns: + Callable[[~.BatchVerifyTargetSitesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_verify_target_sites" not in self._stubs: + self._stubs["batch_verify_target_sites"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/BatchVerifyTargetSites", + request_serializer=site_search_engine_service.BatchVerifyTargetSitesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_verify_target_sites"] + + @property + def fetch_domain_verification_status( + self, + ) -> Callable[ + [site_search_engine_service.FetchDomainVerificationStatusRequest], + Awaitable[site_search_engine_service.FetchDomainVerificationStatusResponse], + ]: + r"""Return a callable for the fetch domain verification + status method over gRPC. + + Returns list of target sites with its domain verification + status. This method can only be called under data store with + BASIC_SITE_SEARCH state at the moment. + + Returns: + Callable[[~.FetchDomainVerificationStatusRequest], + Awaitable[~.FetchDomainVerificationStatusResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_domain_verification_status" not in self._stubs: + self._stubs[ + "fetch_domain_verification_status" + ] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/FetchDomainVerificationStatus", + request_serializer=site_search_engine_service.FetchDomainVerificationStatusRequest.serialize, + response_deserializer=site_search_engine_service.FetchDomainVerificationStatusResponse.deserialize, + ) + return self._stubs["fetch_domain_verification_status"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_site_search_engine: self._wrap_method( + self.get_site_search_engine, + default_timeout=None, + client_info=client_info, + ), + self.create_target_site: self._wrap_method( + self.create_target_site, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_target_sites: self._wrap_method( + self.batch_create_target_sites, + default_timeout=None, + client_info=client_info, + ), + self.get_target_site: self._wrap_method( + self.get_target_site, + default_timeout=None, + client_info=client_info, + ), + self.update_target_site: self._wrap_method( + self.update_target_site, + default_timeout=None, + client_info=client_info, + ), + self.delete_target_site: self._wrap_method( + self.delete_target_site, + default_timeout=None, + client_info=client_info, + ), + self.list_target_sites: self._wrap_method( + self.list_target_sites, + default_timeout=None, + client_info=client_info, + ), + self.create_sitemap: self._wrap_method( + self.create_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.delete_sitemap: self._wrap_method( + self.delete_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.fetch_sitemaps: self._wrap_method( + self.fetch_sitemaps, + default_timeout=None, + client_info=client_info, + ), + self.enable_advanced_site_search: self._wrap_method( + self.enable_advanced_site_search, + default_timeout=None, + client_info=client_info, + ), + self.disable_advanced_site_search: self._wrap_method( + self.disable_advanced_site_search, + default_timeout=None, + client_info=client_info, + ), + self.recrawl_uris: self._wrap_method( + self.recrawl_uris, + default_timeout=None, + client_info=client_info, + ), + self.batch_verify_target_sites: self._wrap_method( + self.batch_verify_target_sites, + default_timeout=None, + client_info=client_info, + ), + self.fetch_domain_verification_status: self._wrap_method( + self.fetch_domain_verification_status, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SiteSearchEngineServiceGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..7d67714be59e8d701f9e8ba0c6969701d093ce85 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py @@ -0,0 +1,4192 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSiteSearchEngineServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SiteSearchEngineServiceRestInterceptor: + """Interceptor for SiteSearchEngineService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SiteSearchEngineServiceRestTransport. + + .. code-block:: python + class MyCustomSiteSearchEngineServiceInterceptor(SiteSearchEngineServiceRestInterceptor): + def pre_batch_create_target_sites(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_target_sites(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_verify_target_sites(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_verify_target_sites(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_sitemap(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sitemap(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_target_site(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_target_site(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sitemap(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_sitemap(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_target_site(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_target_site(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_disable_advanced_site_search(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_advanced_site_search(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_advanced_site_search(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_advanced_site_search(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_domain_verification_status(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_domain_verification_status(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_sitemaps(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_sitemaps(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_site_search_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_site_search_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_target_site(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_target_site(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_target_sites(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_target_sites(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recrawl_uris(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recrawl_uris(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_target_site(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_target_site(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SiteSearchEngineServiceRestTransport(interceptor=MyCustomSiteSearchEngineServiceInterceptor()) + client = SiteSearchEngineServiceClient(transport=transport) + + + """ + + def pre_batch_create_target_sites( + self, + request: site_search_engine_service.BatchCreateTargetSitesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.BatchCreateTargetSitesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_target_sites + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_batch_create_target_sites( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_create_target_sites + + DEPRECATED. Please use the `post_batch_create_target_sites_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_batch_create_target_sites` interceptor runs + before the `post_batch_create_target_sites_with_metadata` interceptor. + """ + return response + + def post_batch_create_target_sites_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for batch_create_target_sites + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_batch_create_target_sites_with_metadata` + interceptor in new development instead of the `post_batch_create_target_sites` interceptor. + When both interceptors are used, this `post_batch_create_target_sites_with_metadata` interceptor runs after the + `post_batch_create_target_sites` interceptor. The (possibly modified) response returned by + `post_batch_create_target_sites` will be passed to + `post_batch_create_target_sites_with_metadata`. + """ + return response, metadata + + def pre_batch_verify_target_sites( + self, + request: site_search_engine_service.BatchVerifyTargetSitesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.BatchVerifyTargetSitesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_verify_target_sites + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_batch_verify_target_sites( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_verify_target_sites + + DEPRECATED. Please use the `post_batch_verify_target_sites_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_batch_verify_target_sites` interceptor runs + before the `post_batch_verify_target_sites_with_metadata` interceptor. + """ + return response + + def post_batch_verify_target_sites_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for batch_verify_target_sites + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_batch_verify_target_sites_with_metadata` + interceptor in new development instead of the `post_batch_verify_target_sites` interceptor. + When both interceptors are used, this `post_batch_verify_target_sites_with_metadata` interceptor runs after the + `post_batch_verify_target_sites` interceptor. The (possibly modified) response returned by + `post_batch_verify_target_sites` will be passed to + `post_batch_verify_target_sites_with_metadata`. + """ + return response, metadata + + def pre_create_sitemap( + self, + request: site_search_engine_service.CreateSitemapRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.CreateSitemapRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_sitemap + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_create_sitemap( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_sitemap + + DEPRECATED. Please use the `post_create_sitemap_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_create_sitemap` interceptor runs + before the `post_create_sitemap_with_metadata` interceptor. + """ + return response + + def post_create_sitemap_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_sitemap + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_create_sitemap_with_metadata` + interceptor in new development instead of the `post_create_sitemap` interceptor. + When both interceptors are used, this `post_create_sitemap_with_metadata` interceptor runs after the + `post_create_sitemap` interceptor. The (possibly modified) response returned by + `post_create_sitemap` will be passed to + `post_create_sitemap_with_metadata`. + """ + return response, metadata + + def pre_create_target_site( + self, + request: site_search_engine_service.CreateTargetSiteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.CreateTargetSiteRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_target_site + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_create_target_site( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_target_site + + DEPRECATED. Please use the `post_create_target_site_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_create_target_site` interceptor runs + before the `post_create_target_site_with_metadata` interceptor. + """ + return response + + def post_create_target_site_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_target_site + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_create_target_site_with_metadata` + interceptor in new development instead of the `post_create_target_site` interceptor. + When both interceptors are used, this `post_create_target_site_with_metadata` interceptor runs after the + `post_create_target_site` interceptor. The (possibly modified) response returned by + `post_create_target_site` will be passed to + `post_create_target_site_with_metadata`. + """ + return response, metadata + + def pre_delete_sitemap( + self, + request: site_search_engine_service.DeleteSitemapRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.DeleteSitemapRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_sitemap + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_delete_sitemap( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_sitemap + + DEPRECATED. Please use the `post_delete_sitemap_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_delete_sitemap` interceptor runs + before the `post_delete_sitemap_with_metadata` interceptor. + """ + return response + + def post_delete_sitemap_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_sitemap + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_delete_sitemap_with_metadata` + interceptor in new development instead of the `post_delete_sitemap` interceptor. + When both interceptors are used, this `post_delete_sitemap_with_metadata` interceptor runs after the + `post_delete_sitemap` interceptor. The (possibly modified) response returned by + `post_delete_sitemap` will be passed to + `post_delete_sitemap_with_metadata`. + """ + return response, metadata + + def pre_delete_target_site( + self, + request: site_search_engine_service.DeleteTargetSiteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.DeleteTargetSiteRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_target_site + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_delete_target_site( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_target_site + + DEPRECATED. Please use the `post_delete_target_site_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_delete_target_site` interceptor runs + before the `post_delete_target_site_with_metadata` interceptor. + """ + return response + + def post_delete_target_site_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_target_site + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_delete_target_site_with_metadata` + interceptor in new development instead of the `post_delete_target_site` interceptor. + When both interceptors are used, this `post_delete_target_site_with_metadata` interceptor runs after the + `post_delete_target_site` interceptor. The (possibly modified) response returned by + `post_delete_target_site` will be passed to + `post_delete_target_site_with_metadata`. + """ + return response, metadata + + def pre_disable_advanced_site_search( + self, + request: site_search_engine_service.DisableAdvancedSiteSearchRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.DisableAdvancedSiteSearchRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for disable_advanced_site_search + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_disable_advanced_site_search( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for disable_advanced_site_search + + DEPRECATED. Please use the `post_disable_advanced_site_search_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_disable_advanced_site_search` interceptor runs + before the `post_disable_advanced_site_search_with_metadata` interceptor. + """ + return response + + def post_disable_advanced_site_search_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for disable_advanced_site_search + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_disable_advanced_site_search_with_metadata` + interceptor in new development instead of the `post_disable_advanced_site_search` interceptor. + When both interceptors are used, this `post_disable_advanced_site_search_with_metadata` interceptor runs after the + `post_disable_advanced_site_search` interceptor. The (possibly modified) response returned by + `post_disable_advanced_site_search` will be passed to + `post_disable_advanced_site_search_with_metadata`. + """ + return response, metadata + + def pre_enable_advanced_site_search( + self, + request: site_search_engine_service.EnableAdvancedSiteSearchRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.EnableAdvancedSiteSearchRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for enable_advanced_site_search + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_enable_advanced_site_search( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for enable_advanced_site_search + + DEPRECATED. Please use the `post_enable_advanced_site_search_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_enable_advanced_site_search` interceptor runs + before the `post_enable_advanced_site_search_with_metadata` interceptor. + """ + return response + + def post_enable_advanced_site_search_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for enable_advanced_site_search + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_enable_advanced_site_search_with_metadata` + interceptor in new development instead of the `post_enable_advanced_site_search` interceptor. + When both interceptors are used, this `post_enable_advanced_site_search_with_metadata` interceptor runs after the + `post_enable_advanced_site_search` interceptor. The (possibly modified) response returned by + `post_enable_advanced_site_search` will be passed to + `post_enable_advanced_site_search_with_metadata`. + """ + return response, metadata + + def pre_fetch_domain_verification_status( + self, + request: site_search_engine_service.FetchDomainVerificationStatusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.FetchDomainVerificationStatusRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_domain_verification_status + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_fetch_domain_verification_status( + self, response: site_search_engine_service.FetchDomainVerificationStatusResponse + ) -> site_search_engine_service.FetchDomainVerificationStatusResponse: + """Post-rpc interceptor for fetch_domain_verification_status + + DEPRECATED. Please use the `post_fetch_domain_verification_status_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_fetch_domain_verification_status` interceptor runs + before the `post_fetch_domain_verification_status_with_metadata` interceptor. + """ + return response + + def post_fetch_domain_verification_status_with_metadata( + self, + response: site_search_engine_service.FetchDomainVerificationStatusResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.FetchDomainVerificationStatusResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_domain_verification_status + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_fetch_domain_verification_status_with_metadata` + interceptor in new development instead of the `post_fetch_domain_verification_status` interceptor. + When both interceptors are used, this `post_fetch_domain_verification_status_with_metadata` interceptor runs after the + `post_fetch_domain_verification_status` interceptor. The (possibly modified) response returned by + `post_fetch_domain_verification_status` will be passed to + `post_fetch_domain_verification_status_with_metadata`. + """ + return response, metadata + + def pre_fetch_sitemaps( + self, + request: site_search_engine_service.FetchSitemapsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.FetchSitemapsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_sitemaps + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_fetch_sitemaps( + self, response: site_search_engine_service.FetchSitemapsResponse + ) -> site_search_engine_service.FetchSitemapsResponse: + """Post-rpc interceptor for fetch_sitemaps + + DEPRECATED. Please use the `post_fetch_sitemaps_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_fetch_sitemaps` interceptor runs + before the `post_fetch_sitemaps_with_metadata` interceptor. + """ + return response + + def post_fetch_sitemaps_with_metadata( + self, + response: site_search_engine_service.FetchSitemapsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.FetchSitemapsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_sitemaps + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_fetch_sitemaps_with_metadata` + interceptor in new development instead of the `post_fetch_sitemaps` interceptor. + When both interceptors are used, this `post_fetch_sitemaps_with_metadata` interceptor runs after the + `post_fetch_sitemaps` interceptor. The (possibly modified) response returned by + `post_fetch_sitemaps` will be passed to + `post_fetch_sitemaps_with_metadata`. + """ + return response, metadata + + def pre_get_site_search_engine( + self, + request: site_search_engine_service.GetSiteSearchEngineRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.GetSiteSearchEngineRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_site_search_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_get_site_search_engine( + self, response: site_search_engine.SiteSearchEngine + ) -> site_search_engine.SiteSearchEngine: + """Post-rpc interceptor for get_site_search_engine + + DEPRECATED. Please use the `post_get_site_search_engine_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_get_site_search_engine` interceptor runs + before the `post_get_site_search_engine_with_metadata` interceptor. + """ + return response + + def post_get_site_search_engine_with_metadata( + self, + response: site_search_engine.SiteSearchEngine, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine.SiteSearchEngine, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_site_search_engine + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_get_site_search_engine_with_metadata` + interceptor in new development instead of the `post_get_site_search_engine` interceptor. + When both interceptors are used, this `post_get_site_search_engine_with_metadata` interceptor runs after the + `post_get_site_search_engine` interceptor. The (possibly modified) response returned by + `post_get_site_search_engine` will be passed to + `post_get_site_search_engine_with_metadata`. + """ + return response, metadata + + def pre_get_target_site( + self, + request: site_search_engine_service.GetTargetSiteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.GetTargetSiteRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_target_site + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_get_target_site( + self, response: site_search_engine.TargetSite + ) -> site_search_engine.TargetSite: + """Post-rpc interceptor for get_target_site + + DEPRECATED. Please use the `post_get_target_site_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_get_target_site` interceptor runs + before the `post_get_target_site_with_metadata` interceptor. + """ + return response + + def post_get_target_site_with_metadata( + self, + response: site_search_engine.TargetSite, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[site_search_engine.TargetSite, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_target_site + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_get_target_site_with_metadata` + interceptor in new development instead of the `post_get_target_site` interceptor. + When both interceptors are used, this `post_get_target_site_with_metadata` interceptor runs after the + `post_get_target_site` interceptor. The (possibly modified) response returned by + `post_get_target_site` will be passed to + `post_get_target_site_with_metadata`. + """ + return response, metadata + + def pre_list_target_sites( + self, + request: site_search_engine_service.ListTargetSitesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.ListTargetSitesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_target_sites + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_list_target_sites( + self, response: site_search_engine_service.ListTargetSitesResponse + ) -> site_search_engine_service.ListTargetSitesResponse: + """Post-rpc interceptor for list_target_sites + + DEPRECATED. Please use the `post_list_target_sites_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_list_target_sites` interceptor runs + before the `post_list_target_sites_with_metadata` interceptor. + """ + return response + + def post_list_target_sites_with_metadata( + self, + response: site_search_engine_service.ListTargetSitesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.ListTargetSitesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_target_sites + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_list_target_sites_with_metadata` + interceptor in new development instead of the `post_list_target_sites` interceptor. + When both interceptors are used, this `post_list_target_sites_with_metadata` interceptor runs after the + `post_list_target_sites` interceptor. The (possibly modified) response returned by + `post_list_target_sites` will be passed to + `post_list_target_sites_with_metadata`. + """ + return response, metadata + + def pre_recrawl_uris( + self, + request: site_search_engine_service.RecrawlUrisRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.RecrawlUrisRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for recrawl_uris + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_recrawl_uris( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for recrawl_uris + + DEPRECATED. Please use the `post_recrawl_uris_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_recrawl_uris` interceptor runs + before the `post_recrawl_uris_with_metadata` interceptor. + """ + return response + + def post_recrawl_uris_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for recrawl_uris + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_recrawl_uris_with_metadata` + interceptor in new development instead of the `post_recrawl_uris` interceptor. + When both interceptors are used, this `post_recrawl_uris_with_metadata` interceptor runs after the + `post_recrawl_uris` interceptor. The (possibly modified) response returned by + `post_recrawl_uris` will be passed to + `post_recrawl_uris_with_metadata`. + """ + return response, metadata + + def pre_update_target_site( + self, + request: site_search_engine_service.UpdateTargetSiteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + site_search_engine_service.UpdateTargetSiteRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_target_site + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_update_target_site( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_target_site + + DEPRECATED. Please use the `post_update_target_site_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. This `post_update_target_site` interceptor runs + before the `post_update_target_site_with_metadata` interceptor. + """ + return response + + def post_update_target_site_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_target_site + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SiteSearchEngineService server but before it is returned to user code. + + We recommend only using this `post_update_target_site_with_metadata` + interceptor in new development instead of the `post_update_target_site` interceptor. + When both interceptors are used, this `post_update_target_site_with_metadata` interceptor runs after the + `post_update_target_site` interceptor. The (possibly modified) response returned by + `post_update_target_site` will be passed to + `post_update_target_site_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SiteSearchEngineServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SiteSearchEngineServiceRestInterceptor + + +class SiteSearchEngineServiceRestTransport(_BaseSiteSearchEngineServiceRestTransport): + """REST backend synchronous transport for SiteSearchEngineService. + + Service for managing site search related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SiteSearchEngineServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SiteSearchEngineServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchCreateTargetSites( + _BaseSiteSearchEngineServiceRestTransport._BaseBatchCreateTargetSites, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.BatchCreateTargetSites") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.BatchCreateTargetSitesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch create target sites method over HTTP. + + Args: + request (~.site_search_engine_service.BatchCreateTargetSitesRequest): + The request object. Request message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseBatchCreateTargetSites._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_create_target_sites( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseBatchCreateTargetSites._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseBatchCreateTargetSites._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseBatchCreateTargetSites._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.BatchCreateTargetSites", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "BatchCreateTargetSites", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._BatchCreateTargetSites._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_target_sites(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_target_sites_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.batch_create_target_sites", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "BatchCreateTargetSites", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchVerifyTargetSites( + _BaseSiteSearchEngineServiceRestTransport._BaseBatchVerifyTargetSites, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.BatchVerifyTargetSites") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.BatchVerifyTargetSitesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch verify target sites method over HTTP. + + Args: + request (~.site_search_engine_service.BatchVerifyTargetSitesRequest): + The request object. Request message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseBatchVerifyTargetSites._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_verify_target_sites( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseBatchVerifyTargetSites._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseBatchVerifyTargetSites._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseBatchVerifyTargetSites._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.BatchVerifyTargetSites", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "BatchVerifyTargetSites", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._BatchVerifyTargetSites._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_verify_target_sites(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_verify_target_sites_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.batch_verify_target_sites", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "BatchVerifyTargetSites", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSitemap( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.CreateSitemap") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.CreateSitemapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create sitemap method over HTTP. + + Args: + request (~.site_search_engine_service.CreateSitemapRequest): + The request object. Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_sitemap(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.CreateSitemap", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "CreateSitemap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._CreateSitemap._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_sitemap(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_sitemap_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.create_sitemap", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "CreateSitemap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateTargetSite( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.CreateTargetSite") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.CreateTargetSiteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create target site method over HTTP. + + Args: + request (~.site_search_engine_service.CreateTargetSiteRequest): + The request object. Request message for + [SiteSearchEngineService.CreateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_target_site( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.CreateTargetSite", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "CreateTargetSite", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._CreateTargetSite._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_target_site(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_target_site_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.create_target_site", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "CreateTargetSite", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSitemap( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.DeleteSitemap") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.DeleteSitemapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete sitemap method over HTTP. + + Args: + request (~.site_search_engine_service.DeleteSitemapRequest): + The request object. Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_sitemap(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.DeleteSitemap", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "DeleteSitemap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._DeleteSitemap._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_sitemap(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_sitemap_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.delete_sitemap", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "DeleteSitemap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteTargetSite( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteTargetSite, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.DeleteTargetSite") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.DeleteTargetSiteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete target site method over HTTP. + + Args: + request (~.site_search_engine_service.DeleteTargetSiteRequest): + The request object. Request message for + [SiteSearchEngineService.DeleteTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteTargetSite] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteTargetSite._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_target_site( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseDeleteTargetSite._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseDeleteTargetSite._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.DeleteTargetSite", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "DeleteTargetSite", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._DeleteTargetSite._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_target_site(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_target_site_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.delete_target_site", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "DeleteTargetSite", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DisableAdvancedSiteSearch( + _BaseSiteSearchEngineServiceRestTransport._BaseDisableAdvancedSiteSearch, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash( + "SiteSearchEngineServiceRestTransport.DisableAdvancedSiteSearch" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.DisableAdvancedSiteSearchRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the disable advanced site + search method over HTTP. + + Args: + request (~.site_search_engine_service.DisableAdvancedSiteSearchRequest): + The request object. Request message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseDisableAdvancedSiteSearch._get_http_options() + ) + + request, metadata = self._interceptor.pre_disable_advanced_site_search( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseDisableAdvancedSiteSearch._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseDisableAdvancedSiteSearch._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseDisableAdvancedSiteSearch._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.DisableAdvancedSiteSearch", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "DisableAdvancedSiteSearch", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._DisableAdvancedSiteSearch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_disable_advanced_site_search(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_disable_advanced_site_search_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.disable_advanced_site_search", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "DisableAdvancedSiteSearch", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _EnableAdvancedSiteSearch( + _BaseSiteSearchEngineServiceRestTransport._BaseEnableAdvancedSiteSearch, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.EnableAdvancedSiteSearch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.EnableAdvancedSiteSearchRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the enable advanced site + search method over HTTP. + + Args: + request (~.site_search_engine_service.EnableAdvancedSiteSearchRequest): + The request object. Request message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseEnableAdvancedSiteSearch._get_http_options() + ) + + request, metadata = self._interceptor.pre_enable_advanced_site_search( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseEnableAdvancedSiteSearch._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseEnableAdvancedSiteSearch._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseEnableAdvancedSiteSearch._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.EnableAdvancedSiteSearch", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "EnableAdvancedSiteSearch", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._EnableAdvancedSiteSearch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_enable_advanced_site_search(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_enable_advanced_site_search_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.enable_advanced_site_search", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "EnableAdvancedSiteSearch", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchDomainVerificationStatus( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchDomainVerificationStatus, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash( + "SiteSearchEngineServiceRestTransport.FetchDomainVerificationStatus" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.FetchDomainVerificationStatusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine_service.FetchDomainVerificationStatusResponse: + r"""Call the fetch domain verification + status method over HTTP. + + Args: + request (~.site_search_engine_service.FetchDomainVerificationStatusRequest): + The request object. Request message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.site_search_engine_service.FetchDomainVerificationStatusResponse: + Response message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchDomainVerificationStatus._get_http_options() + ) + + request, metadata = self._interceptor.pre_fetch_domain_verification_status( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseFetchDomainVerificationStatus._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseFetchDomainVerificationStatus._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.FetchDomainVerificationStatus", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "FetchDomainVerificationStatus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._FetchDomainVerificationStatus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = site_search_engine_service.FetchDomainVerificationStatusResponse() + pb_resp = ( + site_search_engine_service.FetchDomainVerificationStatusResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_domain_verification_status(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_fetch_domain_verification_status_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = site_search_engine_service.FetchDomainVerificationStatusResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.fetch_domain_verification_status", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "FetchDomainVerificationStatus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchSitemaps( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.FetchSitemaps") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.FetchSitemapsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine_service.FetchSitemapsResponse: + r"""Call the fetch sitemaps method over HTTP. + + Args: + request (~.site_search_engine_service.FetchSitemapsRequest): + The request object. Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.site_search_engine_service.FetchSitemapsResponse: + Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_http_options() + ) + + request, metadata = self._interceptor.pre_fetch_sitemaps(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.FetchSitemaps", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "FetchSitemaps", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._FetchSitemaps._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = site_search_engine_service.FetchSitemapsResponse() + pb_resp = site_search_engine_service.FetchSitemapsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_sitemaps(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_sitemaps_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + site_search_engine_service.FetchSitemapsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.fetch_sitemaps", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "FetchSitemaps", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSiteSearchEngine( + _BaseSiteSearchEngineServiceRestTransport._BaseGetSiteSearchEngine, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.GetSiteSearchEngine") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.GetSiteSearchEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine.SiteSearchEngine: + r"""Call the get site search engine method over HTTP. + + Args: + request (~.site_search_engine_service.GetSiteSearchEngineRequest): + The request object. Request message for + [SiteSearchEngineService.GetSiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetSiteSearchEngine] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.site_search_engine.SiteSearchEngine: + SiteSearchEngine captures DataStore + level site search persisting + configurations. It is a singleton value + per data store. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseGetSiteSearchEngine._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_site_search_engine( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseGetSiteSearchEngine._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseGetSiteSearchEngine._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.GetSiteSearchEngine", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "GetSiteSearchEngine", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._GetSiteSearchEngine._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = site_search_engine.SiteSearchEngine() + pb_resp = site_search_engine.SiteSearchEngine.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_site_search_engine(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_site_search_engine_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = site_search_engine.SiteSearchEngine.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.get_site_search_engine", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "GetSiteSearchEngine", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTargetSite( + _BaseSiteSearchEngineServiceRestTransport._BaseGetTargetSite, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.GetTargetSite") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.GetTargetSiteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine.TargetSite: + r"""Call the get target site method over HTTP. + + Args: + request (~.site_search_engine_service.GetTargetSiteRequest): + The request object. Request message for + [SiteSearchEngineService.GetTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetTargetSite] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.site_search_engine.TargetSite: + A target site for the + SiteSearchEngine. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseGetTargetSite._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_target_site(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseGetTargetSite._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseGetTargetSite._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.GetTargetSite", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "GetTargetSite", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._GetTargetSite._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = site_search_engine.TargetSite() + pb_resp = site_search_engine.TargetSite.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_target_site(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_target_site_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = site_search_engine.TargetSite.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.get_target_site", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "GetTargetSite", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTargetSites( + _BaseSiteSearchEngineServiceRestTransport._BaseListTargetSites, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.ListTargetSites") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: site_search_engine_service.ListTargetSitesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> site_search_engine_service.ListTargetSitesResponse: + r"""Call the list target sites method over HTTP. + + Args: + request (~.site_search_engine_service.ListTargetSitesRequest): + The request object. Request message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.site_search_engine_service.ListTargetSitesResponse: + Response message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseListTargetSites._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_target_sites( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseListTargetSites._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseListTargetSites._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.ListTargetSites", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "ListTargetSites", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._ListTargetSites._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = site_search_engine_service.ListTargetSitesResponse() + pb_resp = site_search_engine_service.ListTargetSitesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_target_sites(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_target_sites_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + site_search_engine_service.ListTargetSitesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.list_target_sites", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "ListTargetSites", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RecrawlUris( + _BaseSiteSearchEngineServiceRestTransport._BaseRecrawlUris, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.RecrawlUris") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.RecrawlUrisRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the recrawl uris method over HTTP. + + Args: + request (~.site_search_engine_service.RecrawlUrisRequest): + The request object. Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseRecrawlUris._get_http_options() + ) + + request, metadata = self._interceptor.pre_recrawl_uris(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseRecrawlUris._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseRecrawlUris._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseRecrawlUris._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.RecrawlUris", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "RecrawlUris", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._RecrawlUris._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_recrawl_uris(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_recrawl_uris_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.recrawl_uris", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "RecrawlUris", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateTargetSite( + _BaseSiteSearchEngineServiceRestTransport._BaseUpdateTargetSite, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.UpdateTargetSite") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: site_search_engine_service.UpdateTargetSiteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update target site method over HTTP. + + Args: + request (~.site_search_engine_service.UpdateTargetSiteRequest): + The request object. Request message for + [SiteSearchEngineService.UpdateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.UpdateTargetSite] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseUpdateTargetSite._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_target_site( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseUpdateTargetSite._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseUpdateTargetSite._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseUpdateTargetSite._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.UpdateTargetSite", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "UpdateTargetSite", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._UpdateTargetSite._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_target_site(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_target_site_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.update_target_site", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "UpdateTargetSite", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_create_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchCreateTargetSitesRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateTargetSites(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_verify_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.BatchVerifyTargetSitesRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchVerifyTargetSites(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSitemap(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_target_site( + self, + ) -> Callable[ + [site_search_engine_service.CreateTargetSiteRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateTargetSite(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSitemap(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_target_site( + self, + ) -> Callable[ + [site_search_engine_service.DeleteTargetSiteRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteTargetSite(self._session, self._host, self._interceptor) # type: ignore + + @property + def disable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.DisableAdvancedSiteSearchRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DisableAdvancedSiteSearch(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_advanced_site_search( + self, + ) -> Callable[ + [site_search_engine_service.EnableAdvancedSiteSearchRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EnableAdvancedSiteSearch(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_domain_verification_status( + self, + ) -> Callable[ + [site_search_engine_service.FetchDomainVerificationStatusRequest], + site_search_engine_service.FetchDomainVerificationStatusResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchDomainVerificationStatus(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + site_search_engine_service.FetchSitemapsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchSitemaps(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_site_search_engine( + self, + ) -> Callable[ + [site_search_engine_service.GetSiteSearchEngineRequest], + site_search_engine.SiteSearchEngine, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSiteSearchEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_target_site( + self, + ) -> Callable[ + [site_search_engine_service.GetTargetSiteRequest], site_search_engine.TargetSite + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTargetSite(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_target_sites( + self, + ) -> Callable[ + [site_search_engine_service.ListTargetSitesRequest], + site_search_engine_service.ListTargetSitesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTargetSites(self._session, self._host, self._interceptor) # type: ignore + + @property + def recrawl_uris( + self, + ) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RecrawlUris(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_target_site( + self, + ) -> Callable[ + [site_search_engine_service.UpdateTargetSiteRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateTargetSite(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseSiteSearchEngineServiceRestTransport._BaseCancelOperation, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseSiteSearchEngineServiceRestTransport._BaseGetOperation, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SiteSearchEngineServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseSiteSearchEngineServiceRestTransport._BaseListOperations, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SiteSearchEngineServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4bdd85cce4fbfb3779355301449913b5d0e95675 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py @@ -0,0 +1,1148 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine, + site_search_engine_service, +) + +from .base import DEFAULT_CLIENT_INFO, SiteSearchEngineServiceTransport + + +class _BaseSiteSearchEngineServiceRestTransport(SiteSearchEngineServiceTransport): + """Base REST backend transport for SiteSearchEngineService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchCreateTargetSites: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites:batchCreate", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/targetSites:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.BatchCreateTargetSitesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseBatchCreateTargetSites._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchVerifyTargetSites: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:batchVerifyTargetSites", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.BatchVerifyTargetSitesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseBatchVerifyTargetSites._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSitemap: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/sitemaps", + "body": "sitemap", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/sitemaps", + "body": "sitemap", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.CreateSitemapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateTargetSite: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites", + "body": "target_site", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/targetSites", + "body": "target_site", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.CreateTargetSiteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSitemap: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/sitemaps/*}", + }, + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/sitemaps/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.DeleteSitemapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTargetSite: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}", + }, + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.DeleteTargetSiteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteTargetSite._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDisableAdvancedSiteSearch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/dataStores/*/siteSearchEngine}:disableAdvancedSiteSearch", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:disableAdvancedSiteSearch", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.DisableAdvancedSiteSearchRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseDisableAdvancedSiteSearch._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEnableAdvancedSiteSearch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/dataStores/*/siteSearchEngine}:enableAdvancedSiteSearch", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:enableAdvancedSiteSearch", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.EnableAdvancedSiteSearchRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseEnableAdvancedSiteSearch._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchDomainVerificationStatus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:fetchDomainVerificationStatus", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + site_search_engine_service.FetchDomainVerificationStatusRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchDomainVerificationStatus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchSitemaps: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/sitemaps:fetch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.FetchSitemapsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSiteSearchEngine: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.GetSiteSearchEngineRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseGetSiteSearchEngine._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTargetSite: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.GetTargetSiteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseGetTargetSite._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTargetSites: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites", + }, + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/targetSites", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.ListTargetSitesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseListTargetSites._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRecrawlUris: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/dataStores/*/siteSearchEngine}:recrawlUris", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:recrawlUris", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.RecrawlUrisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseRecrawlUris._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTargetSite: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{target_site.name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}", + "body": "target_site", + }, + { + "method": "patch", + "uri": "/v1beta/{target_site.name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/*}", + "body": "target_site", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.UpdateTargetSiteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseUpdateTargetSite._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSiteSearchEngineServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eea5da67c0134383d3fb18b6f577aff4d3e45e97 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import UserEventServiceAsyncClient +from .client import UserEventServiceClient + +__all__ = ( + "UserEventServiceClient", + "UserEventServiceAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..44ca653a5bfca732eefcead64dca77ed2fd4bee5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py @@ -0,0 +1,939 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + common, + import_config, + purge_config, + user_event, + user_event_service, +) + +from .client import UserEventServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, UserEventServiceTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + _client: UserEventServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = UserEventServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = UserEventServiceClient._DEFAULT_UNIVERSE + + data_store_path = staticmethod(UserEventServiceClient.data_store_path) + parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) + document_path = staticmethod(UserEventServiceClient.document_path) + parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) + engine_path = staticmethod(UserEventServiceClient.engine_path) + parse_engine_path = staticmethod(UserEventServiceClient.parse_engine_path) + common_billing_account_path = staticmethod( + UserEventServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + UserEventServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + UserEventServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + UserEventServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + UserEventServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod( + UserEventServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod( + UserEventServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = UserEventServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, UserEventServiceTransport, Callable[..., UserEventServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,UserEventServiceTransport,Callable[..., UserEventServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the UserEventServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "credentialsType": None, + }, + ) + + async def write_user_event( + self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest, dict]]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with your website. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.write_user_event + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event( + self, + request: Optional[ + Union[user_event_service.CollectUserEventRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest, dict]]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.collect_user_event + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events( + self, + request: Optional[Union[purge_config.PurgeUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_purge_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.PurgeUserEventsRequest, dict]]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.purge_user_events + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events( + self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of user events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest, dict]]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_user_events + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "UserEventServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("UserEventServiceAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..6b36cdf5a50c7b22780a5633547a8aae97093fea --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py @@ -0,0 +1,1415 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + common, + import_config, + purge_config, + user_event, + user_event_service, +) + +from .transports.base import DEFAULT_CLIENT_INFO, UserEventServiceTransport +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .transports.rest import UserEventServiceRestTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserEventServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path( + project: str, + location: str, + data_store: str, + ) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format( + project=project, + location=location, + data_store=data_store, + ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str, str]: + """Parses a data_store path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def document_path( + project: str, + location: str, + data_store: str, + branch: str, + document: str, + ) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str, str]: + """Parses a document path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def engine_path( + project: str, + location: str, + collection: str, + engine: str, + ) -> str: + """Returns a fully-qualified engine string.""" + return "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format( + project=project, + location=location, + collection=collection, + engine=engine, + ) + + @staticmethod + def parse_engine_path(path: str) -> Dict[str, str]: + """Parses a engine path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = UserEventServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = UserEventServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = UserEventServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, UserEventServiceTransport, Callable[..., UserEventServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,UserEventServiceTransport,Callable[..., UserEventServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the UserEventServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = UserEventServiceClient._read_environment_variables() + self._client_cert_source = UserEventServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = UserEventServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, UserEventServiceTransport) + if transport_provided: + # transport is a UserEventServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(UserEventServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or UserEventServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[UserEventServiceTransport], + Callable[..., UserEventServiceTransport], + ] = ( + UserEventServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., UserEventServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1beta.UserEventServiceClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "credentialsType": None, + }, + ) + + def write_user_event( + self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_write_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.discoveryengine_v1beta.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with your website. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event( + self, + request: Optional[ + Union[user_event_service.CollectUserEventRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events( + self, + request: Optional[Union[purge_config.PurgeUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_purge_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + def import_user_events( + self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Bulk import of user events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_import_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserEventServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("UserEventServiceClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..771ec74658ec250f6308d577aa99ac0b2aca6495 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .rest import UserEventServiceRestInterceptor, UserEventServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry["grpc"] = UserEventServiceGrpcTransport +_transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport +_transport_registry["rest"] = UserEventServiceRestTransport + +__all__ = ( + "UserEventServiceTransport", + "UserEventServiceGrpcTransport", + "UserEventServiceGrpcAsyncIOTransport", + "UserEventServiceRestTransport", + "UserEventServiceRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..4b2cf4a6dd668a4a78592a76e2aa4e06f4c70916 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.api import httpbody_pb2 # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version +from google.cloud.discoveryengine_v1beta.types import ( + import_config, + purge_config, + user_event, + user_event_service, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "discoveryengine.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_timeout=None, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( + initial=1.0, + maximum=30.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def write_user_event( + self, + ) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[user_event.UserEvent, Awaitable[user_event.UserEvent]], + ]: + raise NotImplementedError() + + @property + def collect_user_event( + self, + ) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[httpbody_pb2.HttpBody, Awaitable[httpbody_pb2.HttpBody]], + ]: + raise NotImplementedError() + + @property + def purge_user_events( + self, + ) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def import_user_events( + self, + ) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("UserEventServiceTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c945adbc9f45f6ac3018d313b2761a782ad039 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py @@ -0,0 +1,530 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event( + self, + ) -> Callable[[user_event_service.WriteUserEventRequest], user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "write_user_event" not in self._stubs: + self._stubs["write_user_event"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/WriteUserEvent", + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs["write_user_event"] + + @property + def collect_user_event( + self, + ) -> Callable[[user_event_service.CollectUserEventRequest], httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "collect_user_event" not in self._stubs: + self._stubs["collect_user_event"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/CollectUserEvent", + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs["collect_user_event"] + + @property + def purge_user_events( + self, + ) -> Callable[[purge_config.PurgeUserEventsRequest], operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_user_events" not in self._stubs: + self._stubs["purge_user_events"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/PurgeUserEvents", + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["purge_user_events"] + + @property + def import_user_events( + self, + ) -> Callable[[import_config.ImportUserEventsRequest], operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of user events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_user_events" not in self._stubs: + self._stubs["import_user_events"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/ImportUserEvents", + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_user_events"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("UserEventServiceGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..c78d59c6b574e6f36b3c0afcf56ba00367290a96 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event( + self, + ) -> Callable[ + [user_event_service.WriteUserEventRequest], Awaitable[user_event.UserEvent] + ]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "write_user_event" not in self._stubs: + self._stubs["write_user_event"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/WriteUserEvent", + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs["write_user_event"] + + @property + def collect_user_event( + self, + ) -> Callable[ + [user_event_service.CollectUserEventRequest], Awaitable[httpbody_pb2.HttpBody] + ]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "collect_user_event" not in self._stubs: + self._stubs["collect_user_event"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/CollectUserEvent", + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs["collect_user_event"] + + @property + def purge_user_events( + self, + ) -> Callable[ + [purge_config.PurgeUserEventsRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_user_events" not in self._stubs: + self._stubs["purge_user_events"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/PurgeUserEvents", + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["purge_user_events"] + + @property + def import_user_events( + self, + ) -> Callable[ + [import_config.ImportUserEventsRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of user events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_user_events" not in self._stubs: + self._stubs["import_user_events"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.UserEventService/ImportUserEvents", + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_user_events"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.write_user_event: self._wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: self._wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: self._wrap_method( + self.purge_user_events, + default_timeout=None, + client_info=client_info, + ), + self.import_user_events: self._wrap_method( + self.import_user_events, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=30.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("UserEventServiceGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..67098781f71fc429bd4679571f997ca2055d741f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py @@ -0,0 +1,1746 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.discoveryengine_v1beta.types import ( + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseUserEventServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class UserEventServiceRestInterceptor: + """Interceptor for UserEventService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the UserEventServiceRestTransport. + + .. code-block:: python + class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): + def pre_collect_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_collect_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_purge_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_write_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_write_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) + client = UserEventServiceClient(transport=transport) + + + """ + + def pre_collect_user_event( + self, + request: user_event_service.CollectUserEventRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + user_event_service.CollectUserEventRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_collect_user_event( + self, response: httpbody_pb2.HttpBody + ) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for collect_user_event + + DEPRECATED. Please use the `post_collect_user_event_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. This `post_collect_user_event` interceptor runs + before the `post_collect_user_event_with_metadata` interceptor. + """ + return response + + def post_collect_user_event_with_metadata( + self, + response: httpbody_pb2.HttpBody, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[httpbody_pb2.HttpBody, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for collect_user_event + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserEventService server but before it is returned to user code. + + We recommend only using this `post_collect_user_event_with_metadata` + interceptor in new development instead of the `post_collect_user_event` interceptor. + When both interceptors are used, this `post_collect_user_event_with_metadata` interceptor runs after the + `post_collect_user_event` interceptor. The (possibly modified) response returned by + `post_collect_user_event` will be passed to + `post_collect_user_event_with_metadata`. + """ + return response, metadata + + def pre_import_user_events( + self, + request: import_config.ImportUserEventsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + import_config.ImportUserEventsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for import_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_import_user_events( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_user_events + + DEPRECATED. Please use the `post_import_user_events_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. This `post_import_user_events` interceptor runs + before the `post_import_user_events_with_metadata` interceptor. + """ + return response + + def post_import_user_events_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for import_user_events + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserEventService server but before it is returned to user code. + + We recommend only using this `post_import_user_events_with_metadata` + interceptor in new development instead of the `post_import_user_events` interceptor. + When both interceptors are used, this `post_import_user_events_with_metadata` interceptor runs after the + `post_import_user_events` interceptor. The (possibly modified) response returned by + `post_import_user_events` will be passed to + `post_import_user_events_with_metadata`. + """ + return response, metadata + + def pre_purge_user_events( + self, + request: purge_config.PurgeUserEventsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + purge_config.PurgeUserEventsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for purge_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_purge_user_events( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_user_events + + DEPRECATED. Please use the `post_purge_user_events_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. This `post_purge_user_events` interceptor runs + before the `post_purge_user_events_with_metadata` interceptor. + """ + return response + + def post_purge_user_events_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for purge_user_events + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserEventService server but before it is returned to user code. + + We recommend only using this `post_purge_user_events_with_metadata` + interceptor in new development instead of the `post_purge_user_events` interceptor. + When both interceptors are used, this `post_purge_user_events_with_metadata` interceptor runs after the + `post_purge_user_events` interceptor. The (possibly modified) response returned by + `post_purge_user_events` will be passed to + `post_purge_user_events_with_metadata`. + """ + return response, metadata + + def pre_write_user_event( + self, + request: user_event_service.WriteUserEventRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + user_event_service.WriteUserEventRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for write_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_write_user_event( + self, response: user_event.UserEvent + ) -> user_event.UserEvent: + """Post-rpc interceptor for write_user_event + + DEPRECATED. Please use the `post_write_user_event_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. This `post_write_user_event` interceptor runs + before the `post_write_user_event_with_metadata` interceptor. + """ + return response + + def post_write_user_event_with_metadata( + self, + response: user_event.UserEvent, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[user_event.UserEvent, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for write_user_event + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserEventService server but before it is returned to user code. + + We recommend only using this `post_write_user_event_with_metadata` + interceptor in new development instead of the `post_write_user_event` interceptor. + When both interceptors are used, this `post_write_user_event_with_metadata` interceptor runs after the + `post_write_user_event` interceptor. The (possibly modified) response returned by + `post_write_user_event` will be passed to + `post_write_user_event_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class UserEventServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserEventServiceRestInterceptor + + +class UserEventServiceRestTransport(_BaseUserEventServiceRestTransport): + """REST backend synchronous transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[UserEventServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or UserEventServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CollectUserEvent( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent, + UserEventServiceRestStub, + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.CollectUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: user_event_service.CollectUserEventRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Call the collect user event method over HTTP. + + Args: + request (~.user_event_service.CollectUserEventRequest): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_http_options() + ) + + request, metadata = self._interceptor.pre_collect_user_event( + request, metadata + ) + transcoded_request = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.CollectUserEvent", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "CollectUserEvent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._CollectUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_collect_user_event(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_collect_user_event_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.UserEventServiceClient.collect_user_event", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "CollectUserEvent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportUserEvents( + _BaseUserEventServiceRestTransport._BaseImportUserEvents, + UserEventServiceRestStub, + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.ImportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: import_config.ImportUserEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the import user events method over HTTP. + + Args: + request (~.import_config.ImportUserEventsRequest): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_http_options() + ) + + request, metadata = self._interceptor.pre_import_user_events( + request, metadata + ) + transcoded_request = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_transcoded_request( + http_options, request + ) + + body = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.ImportUserEvents", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "ImportUserEvents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._ImportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_user_events(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_import_user_events_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.UserEventServiceClient.import_user_events", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "ImportUserEvents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PurgeUserEvents( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents, + UserEventServiceRestStub, + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.PurgeUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: purge_config.PurgeUserEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the purge user events method over HTTP. + + Args: + request (~.purge_config.PurgeUserEventsRequest): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_http_options() + ) + + request, metadata = self._interceptor.pre_purge_user_events( + request, metadata + ) + transcoded_request = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_transcoded_request( + http_options, request + ) + + body = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.PurgeUserEvents", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "PurgeUserEvents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._PurgeUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_purge_user_events(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_purge_user_events_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.UserEventServiceClient.purge_user_events", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "PurgeUserEvents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _WriteUserEvent( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.WriteUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: user_event_service.WriteUserEventRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user_event.UserEvent: + r"""Call the write user event method over HTTP. + + Args: + request (~.user_event_service.WriteUserEventRequest): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.user_event.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with your website. + + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_http_options() + ) + + request, metadata = self._interceptor.pre_write_user_event( + request, metadata + ) + transcoded_request = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_transcoded_request( + http_options, request + ) + + body = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.WriteUserEvent", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "WriteUserEvent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._WriteUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = user_event.UserEvent() + pb_resp = user_event.UserEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_write_user_event(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_write_user_event_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = user_event.UserEvent.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.UserEventServiceClient.write_user_event", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "WriteUserEvent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def collect_user_event( + self, + ) -> Callable[[user_event_service.CollectUserEventRequest], httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_user_events( + self, + ) -> Callable[[import_config.ImportUserEventsRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def purge_user_events( + self, + ) -> Callable[[purge_config.PurgeUserEventsRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PurgeUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def write_user_event( + self, + ) -> Callable[[user_event_service.WriteUserEventRequest], user_event.UserEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseUserEventServiceRestTransport._BaseCancelOperation, + UserEventServiceRestStub, + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseUserEventServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseUserEventServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseUserEventServiceRestTransport._BaseGetOperation, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseUserEventServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseUserEventServiceRestTransport._BaseListOperations, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseUserEventServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseUserEventServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseUserEventServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.discoveryengine_v1beta.UserEventServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserEventServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1beta.UserEventService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("UserEventServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..88b1391c1cf6c3f329838c2a296bb123cb9cd02d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest_base.py @@ -0,0 +1,545 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.discoveryengine_v1beta.types import ( + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport + + +class _BaseUserEventServiceRestTransport(UserEventServiceTransport): + """Base REST backend transport for UserEventService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCollectUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect", + }, + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect", + }, + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/userEvents:collect", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:import", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:purge", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseWriteUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:write", + "body": "user_event", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write", + "body": "user_event", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/userEvents:write", + "body": "user_event", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseUserEventServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c349abe5f20e24af93ec43db0f339f2c4f684380 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/__init__.py @@ -0,0 +1,516 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .answer import Answer +from .chunk import Chunk +from .common import ( + CustomAttribute, + DoubleList, + EmbeddingConfig, + IndustryVertical, + Interval, + SearchAddOn, + SearchTier, + SearchUseCase, + SolutionType, + UserInfo, +) +from .completion import CompletionSuggestion, SuggestionDenyListEntry +from .completion_service import ( + AdvancedCompleteQueryRequest, + AdvancedCompleteQueryResponse, + CompleteQueryRequest, + CompleteQueryResponse, +) +from .control import Condition, Control +from .control_service import ( + CreateControlRequest, + DeleteControlRequest, + GetControlRequest, + ListControlsRequest, + ListControlsResponse, + UpdateControlRequest, +) +from .conversation import ( + Conversation, + ConversationContext, + ConversationMessage, + Reply, + TextInput, +) +from .conversational_search_service import ( + AnswerQueryRequest, + AnswerQueryResponse, + ConverseConversationRequest, + ConverseConversationResponse, + CreateConversationRequest, + CreateSessionRequest, + DeleteConversationRequest, + DeleteSessionRequest, + GetAnswerRequest, + GetConversationRequest, + GetSessionRequest, + ListConversationsRequest, + ListConversationsResponse, + ListSessionsRequest, + ListSessionsResponse, + UpdateConversationRequest, + UpdateSessionRequest, +) +from .custom_tuning_model import CustomTuningModel +from .data_store import ( + DataStore, + LanguageInfo, + NaturalLanguageQueryUnderstandingConfig, + WorkspaceConfig, +) +from .data_store_service import ( + CreateDataStoreMetadata, + CreateDataStoreRequest, + DeleteDataStoreMetadata, + DeleteDataStoreRequest, + GetDataStoreRequest, + ListDataStoresRequest, + ListDataStoresResponse, + UpdateDataStoreRequest, +) +from .document import Document +from .document_processing_config import DocumentProcessingConfig +from .document_service import ( + BatchGetDocumentsMetadataRequest, + BatchGetDocumentsMetadataResponse, + CreateDocumentRequest, + DeleteDocumentRequest, + GetDocumentRequest, + ListDocumentsRequest, + ListDocumentsResponse, + UpdateDocumentRequest, +) +from .engine import Engine +from .engine_service import ( + CreateEngineMetadata, + CreateEngineRequest, + DeleteEngineMetadata, + DeleteEngineRequest, + GetEngineRequest, + ListEnginesRequest, + ListEnginesResponse, + PauseEngineRequest, + ResumeEngineRequest, + TuneEngineMetadata, + TuneEngineRequest, + TuneEngineResponse, + UpdateEngineRequest, +) +from .evaluation import Evaluation, QualityMetrics +from .evaluation_service import ( + CreateEvaluationMetadata, + CreateEvaluationRequest, + GetEvaluationRequest, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, +) +from .grounded_generation_service import ( + CheckGroundingRequest, + CheckGroundingResponse, + CheckGroundingSpec, + GenerateGroundedContentRequest, + GenerateGroundedContentResponse, + GroundedGenerationContent, +) +from .grounding import FactChunk, GroundingConfig, GroundingFact +from .import_config import ( + AlloyDbSource, + BigQuerySource, + BigtableOptions, + BigtableSource, + CloudSqlSource, + FhirStoreSource, + FirestoreSource, + GcsSource, + ImportCompletionSuggestionsMetadata, + ImportCompletionSuggestionsRequest, + ImportCompletionSuggestionsResponse, + ImportDocumentsMetadata, + ImportDocumentsRequest, + ImportDocumentsResponse, + ImportErrorConfig, + ImportSampleQueriesMetadata, + ImportSampleQueriesRequest, + ImportSampleQueriesResponse, + ImportSuggestionDenyListEntriesMetadata, + ImportSuggestionDenyListEntriesRequest, + ImportSuggestionDenyListEntriesResponse, + ImportUserEventsMetadata, + ImportUserEventsRequest, + ImportUserEventsResponse, + SpannerSource, +) +from .project import Project +from .project_service import ProvisionProjectMetadata, ProvisionProjectRequest +from .purge_config import ( + PurgeCompletionSuggestionsMetadata, + PurgeCompletionSuggestionsRequest, + PurgeCompletionSuggestionsResponse, + PurgeDocumentsMetadata, + PurgeDocumentsRequest, + PurgeDocumentsResponse, + PurgeErrorConfig, + PurgeSuggestionDenyListEntriesMetadata, + PurgeSuggestionDenyListEntriesRequest, + PurgeSuggestionDenyListEntriesResponse, + PurgeUserEventsMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .rank_service import RankingRecord, RankRequest, RankResponse +from .recommendation_service import RecommendRequest, RecommendResponse +from .sample_query import SampleQuery +from .sample_query_service import ( + CreateSampleQueryRequest, + DeleteSampleQueryRequest, + GetSampleQueryRequest, + ListSampleQueriesRequest, + ListSampleQueriesResponse, + UpdateSampleQueryRequest, +) +from .sample_query_set import SampleQuerySet +from .sample_query_set_service import ( + CreateSampleQuerySetRequest, + DeleteSampleQuerySetRequest, + GetSampleQuerySetRequest, + ListSampleQuerySetsRequest, + ListSampleQuerySetsResponse, + UpdateSampleQuerySetRequest, +) +from .schema import Schema +from .schema_service import ( + CreateSchemaMetadata, + CreateSchemaRequest, + DeleteSchemaMetadata, + DeleteSchemaRequest, + GetSchemaRequest, + ListSchemasRequest, + ListSchemasResponse, + UpdateSchemaMetadata, + UpdateSchemaRequest, +) +from .search_service import SearchRequest, SearchResponse +from .search_tuning_service import ( + ListCustomModelsRequest, + ListCustomModelsResponse, + TrainCustomModelMetadata, + TrainCustomModelRequest, + TrainCustomModelResponse, +) +from .serving_config import ServingConfig +from .serving_config_service import ( + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + UpdateServingConfigRequest, +) +from .session import Query, Session +from .site_search_engine import ( + Sitemap, + SiteSearchEngine, + SiteVerificationInfo, + TargetSite, +) +from .site_search_engine_service import ( + BatchCreateTargetSiteMetadata, + BatchCreateTargetSitesRequest, + BatchCreateTargetSitesResponse, + BatchVerifyTargetSitesMetadata, + BatchVerifyTargetSitesRequest, + BatchVerifyTargetSitesResponse, + CreateSitemapMetadata, + CreateSitemapRequest, + CreateTargetSiteMetadata, + CreateTargetSiteRequest, + DeleteSitemapMetadata, + DeleteSitemapRequest, + DeleteTargetSiteMetadata, + DeleteTargetSiteRequest, + DisableAdvancedSiteSearchMetadata, + DisableAdvancedSiteSearchRequest, + DisableAdvancedSiteSearchResponse, + EnableAdvancedSiteSearchMetadata, + EnableAdvancedSiteSearchRequest, + EnableAdvancedSiteSearchResponse, + FetchDomainVerificationStatusRequest, + FetchDomainVerificationStatusResponse, + FetchSitemapsRequest, + FetchSitemapsResponse, + GetSiteSearchEngineRequest, + GetTargetSiteRequest, + ListTargetSitesRequest, + ListTargetSitesResponse, + RecrawlUrisMetadata, + RecrawlUrisRequest, + RecrawlUrisResponse, + UpdateTargetSiteMetadata, + UpdateTargetSiteRequest, +) +from .user_event import ( + CompletionInfo, + DocumentInfo, + MediaInfo, + PageInfo, + PanelInfo, + SearchInfo, + TransactionInfo, + UserEvent, +) +from .user_event_service import CollectUserEventRequest, WriteUserEventRequest + +__all__ = ( + "Answer", + "Chunk", + "CustomAttribute", + "DoubleList", + "EmbeddingConfig", + "Interval", + "UserInfo", + "IndustryVertical", + "SearchAddOn", + "SearchTier", + "SearchUseCase", + "SolutionType", + "CompletionSuggestion", + "SuggestionDenyListEntry", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", + "CompleteQueryRequest", + "CompleteQueryResponse", + "Condition", + "Control", + "CreateControlRequest", + "DeleteControlRequest", + "GetControlRequest", + "ListControlsRequest", + "ListControlsResponse", + "UpdateControlRequest", + "Conversation", + "ConversationContext", + "ConversationMessage", + "Reply", + "TextInput", + "AnswerQueryRequest", + "AnswerQueryResponse", + "ConverseConversationRequest", + "ConverseConversationResponse", + "CreateConversationRequest", + "CreateSessionRequest", + "DeleteConversationRequest", + "DeleteSessionRequest", + "GetAnswerRequest", + "GetConversationRequest", + "GetSessionRequest", + "ListConversationsRequest", + "ListConversationsResponse", + "ListSessionsRequest", + "ListSessionsResponse", + "UpdateConversationRequest", + "UpdateSessionRequest", + "CustomTuningModel", + "DataStore", + "LanguageInfo", + "NaturalLanguageQueryUnderstandingConfig", + "WorkspaceConfig", + "CreateDataStoreMetadata", + "CreateDataStoreRequest", + "DeleteDataStoreMetadata", + "DeleteDataStoreRequest", + "GetDataStoreRequest", + "ListDataStoresRequest", + "ListDataStoresResponse", + "UpdateDataStoreRequest", + "Document", + "DocumentProcessingConfig", + "BatchGetDocumentsMetadataRequest", + "BatchGetDocumentsMetadataResponse", + "CreateDocumentRequest", + "DeleteDocumentRequest", + "GetDocumentRequest", + "ListDocumentsRequest", + "ListDocumentsResponse", + "UpdateDocumentRequest", + "Engine", + "CreateEngineMetadata", + "CreateEngineRequest", + "DeleteEngineMetadata", + "DeleteEngineRequest", + "GetEngineRequest", + "ListEnginesRequest", + "ListEnginesResponse", + "PauseEngineRequest", + "ResumeEngineRequest", + "TuneEngineMetadata", + "TuneEngineRequest", + "TuneEngineResponse", + "UpdateEngineRequest", + "Evaluation", + "QualityMetrics", + "CreateEvaluationMetadata", + "CreateEvaluationRequest", + "GetEvaluationRequest", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "CheckGroundingRequest", + "CheckGroundingResponse", + "CheckGroundingSpec", + "GenerateGroundedContentRequest", + "GenerateGroundedContentResponse", + "GroundedGenerationContent", + "FactChunk", + "GroundingConfig", + "GroundingFact", + "AlloyDbSource", + "BigQuerySource", + "BigtableOptions", + "BigtableSource", + "CloudSqlSource", + "FhirStoreSource", + "FirestoreSource", + "GcsSource", + "ImportCompletionSuggestionsMetadata", + "ImportCompletionSuggestionsRequest", + "ImportCompletionSuggestionsResponse", + "ImportDocumentsMetadata", + "ImportDocumentsRequest", + "ImportDocumentsResponse", + "ImportErrorConfig", + "ImportSampleQueriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", + "ImportSuggestionDenyListEntriesMetadata", + "ImportSuggestionDenyListEntriesRequest", + "ImportSuggestionDenyListEntriesResponse", + "ImportUserEventsMetadata", + "ImportUserEventsRequest", + "ImportUserEventsResponse", + "SpannerSource", + "Project", + "ProvisionProjectMetadata", + "ProvisionProjectRequest", + "PurgeCompletionSuggestionsMetadata", + "PurgeCompletionSuggestionsRequest", + "PurgeCompletionSuggestionsResponse", + "PurgeDocumentsMetadata", + "PurgeDocumentsRequest", + "PurgeDocumentsResponse", + "PurgeErrorConfig", + "PurgeSuggestionDenyListEntriesMetadata", + "PurgeSuggestionDenyListEntriesRequest", + "PurgeSuggestionDenyListEntriesResponse", + "PurgeUserEventsMetadata", + "PurgeUserEventsRequest", + "PurgeUserEventsResponse", + "RankingRecord", + "RankRequest", + "RankResponse", + "RecommendRequest", + "RecommendResponse", + "SampleQuery", + "CreateSampleQueryRequest", + "DeleteSampleQueryRequest", + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "UpdateSampleQueryRequest", + "SampleQuerySet", + "CreateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "UpdateSampleQuerySetRequest", + "Schema", + "CreateSchemaMetadata", + "CreateSchemaRequest", + "DeleteSchemaMetadata", + "DeleteSchemaRequest", + "GetSchemaRequest", + "ListSchemasRequest", + "ListSchemasResponse", + "UpdateSchemaMetadata", + "UpdateSchemaRequest", + "SearchRequest", + "SearchResponse", + "ListCustomModelsRequest", + "ListCustomModelsResponse", + "TrainCustomModelMetadata", + "TrainCustomModelRequest", + "TrainCustomModelResponse", + "ServingConfig", + "GetServingConfigRequest", + "ListServingConfigsRequest", + "ListServingConfigsResponse", + "UpdateServingConfigRequest", + "Query", + "Session", + "Sitemap", + "SiteSearchEngine", + "SiteVerificationInfo", + "TargetSite", + "BatchCreateTargetSiteMetadata", + "BatchCreateTargetSitesRequest", + "BatchCreateTargetSitesResponse", + "BatchVerifyTargetSitesMetadata", + "BatchVerifyTargetSitesRequest", + "BatchVerifyTargetSitesResponse", + "CreateSitemapMetadata", + "CreateSitemapRequest", + "CreateTargetSiteMetadata", + "CreateTargetSiteRequest", + "DeleteSitemapMetadata", + "DeleteSitemapRequest", + "DeleteTargetSiteMetadata", + "DeleteTargetSiteRequest", + "DisableAdvancedSiteSearchMetadata", + "DisableAdvancedSiteSearchRequest", + "DisableAdvancedSiteSearchResponse", + "EnableAdvancedSiteSearchMetadata", + "EnableAdvancedSiteSearchRequest", + "EnableAdvancedSiteSearchResponse", + "FetchDomainVerificationStatusRequest", + "FetchDomainVerificationStatusResponse", + "FetchSitemapsRequest", + "FetchSitemapsResponse", + "GetSiteSearchEngineRequest", + "GetTargetSiteRequest", + "ListTargetSitesRequest", + "ListTargetSitesResponse", + "RecrawlUrisMetadata", + "RecrawlUrisRequest", + "RecrawlUrisResponse", + "UpdateTargetSiteMetadata", + "UpdateTargetSiteRequest", + "CompletionInfo", + "DocumentInfo", + "MediaInfo", + "PageInfo", + "PanelInfo", + "SearchInfo", + "TransactionInfo", + "UserEvent", + "CollectUserEventRequest", + "WriteUserEventRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/answer.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/answer.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a969b6f68491a834dc76958538fa426b9be357 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/answer.py @@ -0,0 +1,749 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Answer", + }, +) + + +class Answer(proto.Message): + r"""Defines an answer. + + Attributes: + name (str): + Immutable. Fully qualified name + ``projects/{project}/locations/global/collections/{collection}/engines/{engine}/sessions/*/answers/*`` + state (google.cloud.discoveryengine_v1beta.types.Answer.State): + The state of the answer generation. + answer_text (str): + The textual answer. + citations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Citation]): + Citations. + references (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Reference]): + References. + related_questions (MutableSequence[str]): + Suggested related questions. + steps (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Step]): + Answer generation steps. + query_understanding_info (google.cloud.discoveryengine_v1beta.types.Answer.QueryUnderstandingInfo): + Query understanding information. + answer_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.AnswerSkippedReason]): + Additional answer-skipped reasons. This + provides the reason for ignored cases. If + nothing is skipped, this field is not set. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Answer creation timestamp. + complete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Answer completed timestamp. + """ + + class State(proto.Enum): + r"""Enumeration of the state of the answer generation. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + IN_PROGRESS (1): + Answer generation is currently in progress. + FAILED (2): + Answer generation currently failed. + SUCCEEDED (3): + Answer generation has succeeded. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + FAILED = 2 + SUCCEEDED = 3 + + class AnswerSkippedReason(proto.Enum): + r"""An enum for answer skipped reasons. + + Values: + ANSWER_SKIPPED_REASON_UNSPECIFIED (0): + Default value. The answer skipped reason is + not specified. + ADVERSARIAL_QUERY_IGNORED (1): + The adversarial query ignored case. + NON_ANSWER_SEEKING_QUERY_IGNORED (2): + The non-answer seeking query ignored case + + Google skips the answer if the query is chit + chat. + OUT_OF_DOMAIN_QUERY_IGNORED (3): + The out-of-domain query ignored case. + + Google skips the answer if there are no + high-relevance search results. + POTENTIAL_POLICY_VIOLATION (4): + The potential policy violation case. + + Google skips the answer if there is a potential + policy violation detected. This includes content + that may be violent or toxic. + NO_RELEVANT_CONTENT (5): + The no relevant content case. + + Google skips the answer if there is no relevant + content in the retrieved search results. + JAIL_BREAKING_QUERY_IGNORED (6): + The jail-breaking query ignored case. + + For example, "Reply in the tone of a competing + company's CEO". Google skips the answer if the + query is classified as a jail-breaking query. + CUSTOMER_POLICY_VIOLATION (7): + The customer policy violation case. + + Google skips the summary if there is a customer + policy violation detected. The policy is defined + by the customer. + NON_ANSWER_SEEKING_QUERY_IGNORED_V2 (8): + The non-answer seeking query ignored case. + + Google skips the answer if the query doesn't + have clear intent. + LOW_GROUNDED_ANSWER (9): + The low-grounded answer case. + + Google skips the answer if a well grounded + answer was unable to be generated. + """ + ANSWER_SKIPPED_REASON_UNSPECIFIED = 0 + ADVERSARIAL_QUERY_IGNORED = 1 + NON_ANSWER_SEEKING_QUERY_IGNORED = 2 + OUT_OF_DOMAIN_QUERY_IGNORED = 3 + POTENTIAL_POLICY_VIOLATION = 4 + NO_RELEVANT_CONTENT = 5 + JAIL_BREAKING_QUERY_IGNORED = 6 + CUSTOMER_POLICY_VIOLATION = 7 + NON_ANSWER_SEEKING_QUERY_IGNORED_V2 = 8 + LOW_GROUNDED_ANSWER = 9 + + class Citation(proto.Message): + r"""Citation info for a segment. + + Attributes: + start_index (int): + Index indicates the start of the segment, + measured in bytes (UTF-8 unicode). + end_index (int): + End of the attributed segment, exclusive. + sources (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.CitationSource]): + Citation sources for the attributed segment. + """ + + start_index: int = proto.Field( + proto.INT64, + number=1, + ) + end_index: int = proto.Field( + proto.INT64, + number=2, + ) + sources: MutableSequence["Answer.CitationSource"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Answer.CitationSource", + ) + + class CitationSource(proto.Message): + r"""Citation source. + + Attributes: + reference_id (str): + ID of the citation source. + """ + + reference_id: str = proto.Field( + proto.STRING, + number=1, + ) + + class Reference(proto.Message): + r"""Reference. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + unstructured_document_info (google.cloud.discoveryengine_v1beta.types.Answer.Reference.UnstructuredDocumentInfo): + Unstructured document information. + + This field is a member of `oneof`_ ``content``. + chunk_info (google.cloud.discoveryengine_v1beta.types.Answer.Reference.ChunkInfo): + Chunk information. + + This field is a member of `oneof`_ ``content``. + structured_document_info (google.cloud.discoveryengine_v1beta.types.Answer.Reference.StructuredDocumentInfo): + Structured document information. + + This field is a member of `oneof`_ ``content``. + """ + + class UnstructuredDocumentInfo(proto.Message): + r"""Unstructured document information. + + Attributes: + document (str): + Document resource name. + uri (str): + URI for the document. + title (str): + Title. + chunk_contents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Reference.UnstructuredDocumentInfo.ChunkContent]): + List of cited chunk contents derived from + document content. + struct_data (google.protobuf.struct_pb2.Struct): + The structured JSON metadata for the + document. It is populated from the struct data + from the Chunk in search result. + """ + + class ChunkContent(proto.Message): + r"""Chunk content. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content (str): + Chunk textual content. + page_identifier (str): + Page identifier. + relevance_score (float): + The relevance of the chunk for a given query. + Values range from 0.0 (completely irrelevant) to + 1.0 (completely relevant). This value is for + informational purpose only. It may change for + the same query and chunk at any time due to a + model retraining or change in implementation. + + This field is a member of `oneof`_ ``_relevance_score``. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + page_identifier: str = proto.Field( + proto.STRING, + number=2, + ) + relevance_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + + document: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + chunk_contents: MutableSequence[ + "Answer.Reference.UnstructuredDocumentInfo.ChunkContent" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Answer.Reference.UnstructuredDocumentInfo.ChunkContent", + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + + class ChunkInfo(proto.Message): + r"""Chunk information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + chunk (str): + Chunk resource name. + content (str): + Chunk textual content. + relevance_score (float): + The relevance of the chunk for a given query. + Values range from 0.0 (completely irrelevant) to + 1.0 (completely relevant). This value is for + informational purpose only. It may change for + the same query and chunk at any time due to a + model retraining or change in implementation. + + This field is a member of `oneof`_ ``_relevance_score``. + document_metadata (google.cloud.discoveryengine_v1beta.types.Answer.Reference.ChunkInfo.DocumentMetadata): + Document metadata. + """ + + class DocumentMetadata(proto.Message): + r"""Document metadata. + + Attributes: + document (str): + Document resource name. + uri (str): + URI for the document. + title (str): + Title. + page_identifier (str): + Page identifier. + struct_data (google.protobuf.struct_pb2.Struct): + The structured JSON metadata for the + document. It is populated from the struct data + from the Chunk in search result. + """ + + document: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + page_identifier: str = proto.Field( + proto.STRING, + number=4, + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + + chunk: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + relevance_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + document_metadata: "Answer.Reference.ChunkInfo.DocumentMetadata" = ( + proto.Field( + proto.MESSAGE, + number=4, + message="Answer.Reference.ChunkInfo.DocumentMetadata", + ) + ) + + class StructuredDocumentInfo(proto.Message): + r"""Structured search information. + + Attributes: + document (str): + Document resource name. + struct_data (google.protobuf.struct_pb2.Struct): + Structured search data. + """ + + document: str = proto.Field( + proto.STRING, + number=1, + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + + unstructured_document_info: "Answer.Reference.UnstructuredDocumentInfo" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="content", + message="Answer.Reference.UnstructuredDocumentInfo", + ) + ) + chunk_info: "Answer.Reference.ChunkInfo" = proto.Field( + proto.MESSAGE, + number=2, + oneof="content", + message="Answer.Reference.ChunkInfo", + ) + structured_document_info: "Answer.Reference.StructuredDocumentInfo" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="content", + message="Answer.Reference.StructuredDocumentInfo", + ) + ) + + class Step(proto.Message): + r"""Step information. + + Attributes: + state (google.cloud.discoveryengine_v1beta.types.Answer.Step.State): + The state of the step. + description (str): + The description of the step. + thought (str): + The thought of the step. + actions (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Step.Action]): + Actions. + """ + + class State(proto.Enum): + r"""Enumeration of the state of the step. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + IN_PROGRESS (1): + Step is currently in progress. + FAILED (2): + Step currently failed. + SUCCEEDED (3): + Step has succeeded. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + FAILED = 2 + SUCCEEDED = 3 + + class Action(proto.Message): + r"""Action. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_action (google.cloud.discoveryengine_v1beta.types.Answer.Step.Action.SearchAction): + Search action. + + This field is a member of `oneof`_ ``action``. + observation (google.cloud.discoveryengine_v1beta.types.Answer.Step.Action.Observation): + Observation. + """ + + class SearchAction(proto.Message): + r"""Search action. + + Attributes: + query (str): + The query to search. + """ + + query: str = proto.Field( + proto.STRING, + number=1, + ) + + class Observation(proto.Message): + r"""Observation. + + Attributes: + search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Step.Action.Observation.SearchResult]): + Search results observed by the search action, + it can be snippets info or chunk info, depending + on the citation type set by the user. + """ + + class SearchResult(proto.Message): + r""" + + Attributes: + document (str): + Document resource name. + uri (str): + URI for the document. + title (str): + Title. + snippet_info (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Step.Action.Observation.SearchResult.SnippetInfo]): + If citation_type is DOCUMENT_LEVEL_CITATION, populate + document level snippets. + chunk_info (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.Step.Action.Observation.SearchResult.ChunkInfo]): + If citation_type is CHUNK_LEVEL_CITATION and chunk mode is + on, populate chunk info. + struct_data (google.protobuf.struct_pb2.Struct): + Data representation. + The structured JSON data for the document. + It's populated from the struct data from the + Document, or the Chunk in search result. + """ + + class SnippetInfo(proto.Message): + r"""Snippet information. + + Attributes: + snippet (str): + Snippet content. + snippet_status (str): + Status of the snippet defined by the search + team. + """ + + snippet: str = proto.Field( + proto.STRING, + number=1, + ) + snippet_status: str = proto.Field( + proto.STRING, + number=2, + ) + + class ChunkInfo(proto.Message): + r"""Chunk information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + chunk (str): + Chunk resource name. + content (str): + Chunk textual content. + relevance_score (float): + The relevance of the chunk for a given query. + Values range from 0.0 (completely irrelevant) to + 1.0 (completely relevant). This value is for + informational purpose only. It may change for + the same query and chunk at any time due to a + model retraining or change in implementation. + + This field is a member of `oneof`_ ``_relevance_score``. + """ + + chunk: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + relevance_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + + document: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + snippet_info: MutableSequence[ + "Answer.Step.Action.Observation.SearchResult.SnippetInfo" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Answer.Step.Action.Observation.SearchResult.SnippetInfo", + ) + chunk_info: MutableSequence[ + "Answer.Step.Action.Observation.SearchResult.ChunkInfo" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Answer.Step.Action.Observation.SearchResult.ChunkInfo", + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + search_results: MutableSequence[ + "Answer.Step.Action.Observation.SearchResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Answer.Step.Action.Observation.SearchResult", + ) + + search_action: "Answer.Step.Action.SearchAction" = proto.Field( + proto.MESSAGE, + number=2, + oneof="action", + message="Answer.Step.Action.SearchAction", + ) + observation: "Answer.Step.Action.Observation" = proto.Field( + proto.MESSAGE, + number=3, + message="Answer.Step.Action.Observation", + ) + + state: "Answer.Step.State" = proto.Field( + proto.ENUM, + number=1, + enum="Answer.Step.State", + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + thought: str = proto.Field( + proto.STRING, + number=3, + ) + actions: MutableSequence["Answer.Step.Action"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Answer.Step.Action", + ) + + class QueryUnderstandingInfo(proto.Message): + r"""Query understanding information. + + Attributes: + query_classification_info (MutableSequence[google.cloud.discoveryengine_v1beta.types.Answer.QueryUnderstandingInfo.QueryClassificationInfo]): + Query classification information. + """ + + class QueryClassificationInfo(proto.Message): + r"""Query classification information. + + Attributes: + type_ (google.cloud.discoveryengine_v1beta.types.Answer.QueryUnderstandingInfo.QueryClassificationInfo.Type): + Query classification type. + positive (bool): + Classification output. + """ + + class Type(proto.Enum): + r"""Query classification types. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified query classification type. + ADVERSARIAL_QUERY (1): + Adversarial query classification type. + NON_ANSWER_SEEKING_QUERY (2): + Non-answer-seeking query classification type, + for chit chat. + JAIL_BREAKING_QUERY (3): + Jail-breaking query classification type. + NON_ANSWER_SEEKING_QUERY_V2 (4): + Non-answer-seeking query classification type, + for no clear intent. + """ + TYPE_UNSPECIFIED = 0 + ADVERSARIAL_QUERY = 1 + NON_ANSWER_SEEKING_QUERY = 2 + JAIL_BREAKING_QUERY = 3 + NON_ANSWER_SEEKING_QUERY_V2 = 4 + + type_: "Answer.QueryUnderstandingInfo.QueryClassificationInfo.Type" = ( + proto.Field( + proto.ENUM, + number=1, + enum="Answer.QueryUnderstandingInfo.QueryClassificationInfo.Type", + ) + ) + positive: bool = proto.Field( + proto.BOOL, + number=2, + ) + + query_classification_info: MutableSequence[ + "Answer.QueryUnderstandingInfo.QueryClassificationInfo" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Answer.QueryUnderstandingInfo.QueryClassificationInfo", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + answer_text: str = proto.Field( + proto.STRING, + number=3, + ) + citations: MutableSequence[Citation] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Citation, + ) + references: MutableSequence[Reference] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Reference, + ) + related_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + steps: MutableSequence[Step] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Step, + ) + query_understanding_info: QueryUnderstandingInfo = proto.Field( + proto.MESSAGE, + number=10, + message=QueryUnderstandingInfo, + ) + answer_skipped_reasons: MutableSequence[AnswerSkippedReason] = proto.RepeatedField( + proto.ENUM, + number=11, + enum=AnswerSkippedReason, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + complete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/chunk.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..495c1b461a8488877dcb2b6f5e5b31bdbb1c0ff6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/chunk.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Chunk", + }, +) + + +class Chunk(proto.Message): + r"""Chunk captures all raw metadata information of items to be + recommended or searched in the chunk mode. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The full resource name of the chunk. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}/chunks/{chunk_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + id (str): + Unique chunk ID of the current chunk. + content (str): + Content is a string from a document (parsed + content). + relevance_score (float): + Output only. Represents the relevance score based on + similarity. Higher score indicates higher chunk relevance. + The score is in range [-1.0, 1.0]. Only populated on + [SearchService.SearchResponse][]. + + This field is a member of `oneof`_ ``_relevance_score``. + document_metadata (google.cloud.discoveryengine_v1beta.types.Chunk.DocumentMetadata): + Metadata of the document from the current + chunk. + derived_struct_data (google.protobuf.struct_pb2.Struct): + Output only. This field is OUTPUT_ONLY. It contains derived + data that are not in the original input document. + page_span (google.cloud.discoveryengine_v1beta.types.Chunk.PageSpan): + Page span of the chunk. + chunk_metadata (google.cloud.discoveryengine_v1beta.types.Chunk.ChunkMetadata): + Output only. Metadata of the current chunk. + """ + + class DocumentMetadata(proto.Message): + r"""Document metadata contains the information of the document of + the current chunk. + + Attributes: + uri (str): + Uri of the document. + title (str): + Title of the document. + struct_data (google.protobuf.struct_pb2.Struct): + Data representation. The structured JSON data for the + document. It should conform to the registered + [Schema][google.cloud.discoveryengine.v1beta.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + class PageSpan(proto.Message): + r"""Page span of the chunk. + + Attributes: + page_start (int): + The start page of the chunk. + page_end (int): + The end page of the chunk. + """ + + page_start: int = proto.Field( + proto.INT32, + number=1, + ) + page_end: int = proto.Field( + proto.INT32, + number=2, + ) + + class ChunkMetadata(proto.Message): + r"""Metadata of the current chunk. This field is only populated on + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API. + + Attributes: + previous_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.Chunk]): + The previous chunks of the current chunk. The number is + controlled by + [SearchRequest.ContentSearchSpec.ChunkSpec.num_previous_chunks][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.ChunkSpec.num_previous_chunks]. + This field is only populated on + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API. + next_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.Chunk]): + The next chunks of the current chunk. The number is + controlled by + [SearchRequest.ContentSearchSpec.ChunkSpec.num_next_chunks][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.ChunkSpec.num_next_chunks]. + This field is only populated on + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API. + """ + + previous_chunks: MutableSequence["Chunk"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Chunk", + ) + next_chunks: MutableSequence["Chunk"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Chunk", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + content: str = proto.Field( + proto.STRING, + number=3, + ) + relevance_score: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + document_metadata: DocumentMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=DocumentMetadata, + ) + derived_struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + page_span: PageSpan = proto.Field( + proto.MESSAGE, + number=6, + message=PageSpan, + ) + chunk_metadata: ChunkMetadata = proto.Field( + proto.MESSAGE, + number=7, + message=ChunkMetadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/common.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/common.py new file mode 100644 index 0000000000000000000000000000000000000000..77a3ec8f1d3f57e9f1f34841f5d7210ef4f5fe55 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/common.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "IndustryVertical", + "SolutionType", + "SearchUseCase", + "SearchTier", + "SearchAddOn", + "Interval", + "CustomAttribute", + "UserInfo", + "EmbeddingConfig", + "DoubleList", + }, +) + + +class IndustryVertical(proto.Enum): + r"""The industry vertical associated with the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Values: + INDUSTRY_VERTICAL_UNSPECIFIED (0): + Value used when unset. + GENERIC (1): + The generic vertical for documents that are + not specific to any industry vertical. + MEDIA (2): + The media industry vertical. + HEALTHCARE_FHIR (7): + The healthcare FHIR vertical. + """ + INDUSTRY_VERTICAL_UNSPECIFIED = 0 + GENERIC = 1 + MEDIA = 2 + HEALTHCARE_FHIR = 7 + + +class SolutionType(proto.Enum): + r"""The type of solution. + + Values: + SOLUTION_TYPE_UNSPECIFIED (0): + Default value. + SOLUTION_TYPE_RECOMMENDATION (1): + Used for Recommendations AI. + SOLUTION_TYPE_SEARCH (2): + Used for Discovery Search. + SOLUTION_TYPE_CHAT (3): + Used for use cases related to the Generative + AI agent. + SOLUTION_TYPE_GENERATIVE_CHAT (4): + Used for use cases related to the Generative Chat agent. + It's used for Generative chat engine only, the associated + data stores must enrolled with ``SOLUTION_TYPE_CHAT`` + solution. + """ + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + SOLUTION_TYPE_CHAT = 3 + SOLUTION_TYPE_GENERATIVE_CHAT = 4 + + +class SearchUseCase(proto.Enum): + r"""Defines a further subdivision of ``SolutionType``. Specifically + applies to + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + + Values: + SEARCH_USE_CASE_UNSPECIFIED (0): + Value used when unset. Will not occur in CSS. + SEARCH_USE_CASE_SEARCH (1): + Search use case. Expects the traffic has a non-empty + [query][google.cloud.discoveryengine.v1beta.SearchRequest.query]. + SEARCH_USE_CASE_BROWSE (2): + Browse use case. Expects the traffic has an empty + [query][google.cloud.discoveryengine.v1beta.SearchRequest.query]. + """ + SEARCH_USE_CASE_UNSPECIFIED = 0 + SEARCH_USE_CASE_SEARCH = 1 + SEARCH_USE_CASE_BROWSE = 2 + + +class SearchTier(proto.Enum): + r"""Tiers of search features. Different tiers might have + different pricing. To learn more, check the pricing + documentation. + + Values: + SEARCH_TIER_UNSPECIFIED (0): + Default value when the enum is unspecified. + This is invalid to use. + SEARCH_TIER_STANDARD (1): + Standard tier. + SEARCH_TIER_ENTERPRISE (2): + Enterprise tier. + """ + SEARCH_TIER_UNSPECIFIED = 0 + SEARCH_TIER_STANDARD = 1 + SEARCH_TIER_ENTERPRISE = 2 + + +class SearchAddOn(proto.Enum): + r"""Add-on that provides additional functionality for search. + + Values: + SEARCH_ADD_ON_UNSPECIFIED (0): + Default value when the enum is unspecified. + This is invalid to use. + SEARCH_ADD_ON_LLM (1): + Large language model add-on. + """ + SEARCH_ADD_ON_UNSPECIFIED = 0 + SEARCH_ADD_ON_LLM = 1 + + +class Interval(proto.Message): + r"""A floating point interval. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum: float = proto.Field( + proto.DOUBLE, + number=1, + oneof="min", + ) + exclusive_minimum: float = proto.Field( + proto.DOUBLE, + number=2, + oneof="min", + ) + maximum: float = proto.Field( + proto.DOUBLE, + number=3, + oneof="max", + ) + exclusive_maximum: float = proto.Field( + proto.DOUBLE, + number=4, + oneof="max", + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in a resource, + e.g. [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent]. + + Attributes: + text (MutableSequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1beta.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1beta.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + numbers (MutableSequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1beta.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1beta.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + """ + + text: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + user_agent (str): + User agent as included in the HTTP header. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent] + or if + [UserEvent.direct_user_request][google.cloud.discoveryengine.v1beta.UserEvent.direct_user_request] + is set. + """ + + user_id: str = proto.Field( + proto.STRING, + number=1, + ) + user_agent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class EmbeddingConfig(proto.Message): + r"""Defines embedding config, used for bring your own embeddings + feature. + + Attributes: + field_path (str): + Full field path in the schema mapped as + embedding field. + """ + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DoubleList(proto.Message): + r"""Double list. + + Attributes: + values (MutableSequence[float]): + Double values. + """ + + values: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/completion.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8b684bf6a30dcb2c36fbb29c308b104fd7705f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/completion.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SuggestionDenyListEntry", + "CompletionSuggestion", + }, +) + + +class SuggestionDenyListEntry(proto.Message): + r"""Suggestion deny list entry identifying the phrase to block + from suggestions and the applied operation for the phrase. + + Attributes: + block_phrase (str): + Required. Phrase to block from suggestions + served. Can be maximum 125 characters. + match_operator (google.cloud.discoveryengine_v1beta.types.SuggestionDenyListEntry.MatchOperator): + Required. The match operator to apply for + this phrase. Whether to block the exact phrase, + or block any suggestions containing this phrase. + """ + + class MatchOperator(proto.Enum): + r"""Operator for matching with the generated suggestions. + + Values: + MATCH_OPERATOR_UNSPECIFIED (0): + Default value. Should not be used + EXACT_MATCH (1): + If the suggestion is an exact match to the block_phrase, + then block it. + CONTAINS (2): + If the suggestion contains the block_phrase, then block it. + """ + MATCH_OPERATOR_UNSPECIFIED = 0 + EXACT_MATCH = 1 + CONTAINS = 2 + + block_phrase: str = proto.Field( + proto.STRING, + number=1, + ) + match_operator: MatchOperator = proto.Field( + proto.ENUM, + number=2, + enum=MatchOperator, + ) + + +class CompletionSuggestion(proto.Message): + r"""Autocomplete suggestions that are imported from Customer. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + global_score (float): + Global score of this suggestion. Control how + this suggestion would be scored / ranked. + + This field is a member of `oneof`_ ``ranking_info``. + frequency (int): + Frequency of this suggestion. Will be used to + rank suggestions when score is not available. + + This field is a member of `oneof`_ ``ranking_info``. + suggestion (str): + Required. The suggestion text. + language_code (str): + BCP-47 language code of this suggestion. + group_id (str): + If two suggestions have the same groupId, + they will not be returned together. Instead the + one ranked higher will be returned. This can be + used to deduplicate semantically identical + suggestions. + group_score (float): + The score of this suggestion within its + group. + alternative_phrases (MutableSequence[str]): + Alternative matching phrases for this + suggestion. + """ + + global_score: float = proto.Field( + proto.DOUBLE, + number=2, + oneof="ranking_info", + ) + frequency: int = proto.Field( + proto.INT64, + number=3, + oneof="ranking_info", + ) + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + group_id: str = proto.Field( + proto.STRING, + number=5, + ) + group_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + alternative_phrases: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/completion_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/completion_service.py new file mode 100644 index 0000000000000000000000000000000000000000..e577c83b84f4d9ecad1aab45826827c30deb470c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/completion_service.py @@ -0,0 +1,601 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import document as gcd_document + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "CompleteQueryRequest", + "CompleteQueryResponse", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + Attributes: + data_store (str): + Required. The parent data store resource name for which the + completion is performed, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. + query (str): + Required. The typeahead input used to fetch + suggestions. Maximum length is 128 characters. + query_model (str): + Specifies the autocomplete data model. This overrides any + model specified in the Configuration > Autocomplete section + of the Cloud console. Currently supported values: + + - ``document`` - Using suggestions generated from + user-imported documents. + - ``search-history`` - Using suggestions generated from the + past history of + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API calls. Do not use it when there is no traffic for + Search API. + - ``user-event`` - Using suggestions generated from + user-imported search events. + - ``document-completable`` - Using suggestions taken + directly from user-imported document fields marked as + completable. + + Default values: + + - ``document`` is the default model for regular dataStores. + - ``search-history`` is the default model for site search + dataStores. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + and + [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + include_tail_suggestions (bool): + Indicates if tail suggestions should be + returned if there are no suggestions that match + the full query. Even if set to true, if there + are suggestions that match the full query, those + are returned and no tail suggestions are + returned. + """ + + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + query_model: str = proto.Field( + proto.STRING, + number=3, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=4, + ) + include_tail_suggestions: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + Attributes: + query_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse.QuerySuggestion]): + Results of the matched query suggestions. The + result list is ordered and the first result is a + top suggestion. + tail_match_triggered (bool): + True if the returned suggestions are all tail suggestions. + + For tail matching to be triggered, include_tail_suggestions + in the request must be true and there must be no suggestions + that match the full query. + """ + + class QuerySuggestion(proto.Message): + r"""Suggestions as search queries. + + Attributes: + suggestion (str): + The suggestion for the query. + completable_field_paths (MutableSequence[str]): + The unique document field paths that serve as + the source of this suggestion if it was + generated from completable fields. + + This field is only populated for the + document-completable model. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + completable_field_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QuerySuggestion, + ) + tail_match_triggered: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class AdvancedCompleteQueryRequest(proto.Message): + r"""Request message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. . + + Attributes: + completion_config (str): + Required. The completion_config of the parent dataStore or + engine resource name for which the completion is performed, + such as + ``projects/*/locations/global/collections/default_collection/dataStores/*/completionConfig`` + ``projects/*/locations/global/collections/default_collection/engines/*/completionConfig``. + query (str): + Required. The typeahead input used to fetch suggestions. + Maximum length is 128 characters. + + The query can not be empty for most of the suggestion types. + If it is empty, an ``INVALID_ARGUMENT`` error is returned. + The exception is when the suggestion_types contains only the + type ``RECENT_SEARCH``, the query can be an empty string. + The is called "zero prefix" feature, which returns user's + recently searched queries given the empty query. + query_model (str): + Specifies the autocomplete data model. This overrides any + model specified in the Configuration > Autocomplete section + of the Cloud console. Currently supported values: + + - ``document`` - Using suggestions generated from + user-imported documents. + - ``search-history`` - Using suggestions generated from the + past history of + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API calls. Do not use it when there is no traffic for + Search API. + - ``user-event`` - Using suggestions generated from + user-imported search events. + - ``document-completable`` - Using suggestions taken + directly from user-imported document fields marked as + completable. + + Default values: + + - ``document`` is the default model for regular dataStores. + - ``search-history`` is the default model for site search + dataStores. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + and + [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 + user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): + Optional. Information about the end user. + + This should be the same identifier information as + [UserEvent.user_info][google.cloud.discoveryengine.v1beta.UserEvent.user_info] + and + [SearchRequest.user_info][google.cloud.discoveryengine.v1beta.SearchRequest.user_info]. + include_tail_suggestions (bool): + Indicates if tail suggestions should be + returned if there are no suggestions that match + the full query. Even if set to true, if there + are suggestions that match the full query, those + are returned and no tail suggestions are + returned. + boost_spec (google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest.BoostSpec): + Optional. Specification to boost suggestions + matching the condition. + suggestion_types (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest.SuggestionType]): + Optional. Suggestion types to return. If + empty or unspecified, query suggestions are + returned. Only one suggestion type is supported + at the moment. + """ + + class SuggestionType(proto.Enum): + r"""Suggestion type to return. + + Values: + SUGGESTION_TYPE_UNSPECIFIED (0): + Default value. + QUERY (1): + Returns query suggestions. + PEOPLE (2): + Returns people suggestions. + CONTENT (3): + Returns content suggestions. + RECENT_SEARCH (4): + Returns recent search suggestions. + GOOGLE_WORKSPACE (5): + Returns Google Workspace suggestions. + """ + SUGGESTION_TYPE_UNSPECIFIED = 0 + QUERY = 1 + PEOPLE = 2 + CONTENT = 3 + RECENT_SEARCH = 4 + GOOGLE_WORKSPACE = 5 + + class BoostSpec(proto.Message): + r"""Specification to boost suggestions based on the condtion of + the suggestion. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a + suggestion matches multiple conditions in the + specifictions, boost values from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + + Note: Currently only support language condition + boost. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to suggestions which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + is the same as `filter expression + syntax `__. + Currently, the only supported condition is a list of BCP-47 + lang codes. + + Example: + + - To boost suggestions in languages ``en`` or ``fr``: + ``(lang_code: ANY("en", "fr"))`` + boost (float): + Strength of the boost, which should be in [-1, 1]. Negative + boost means demotion. Default is 0.0. + + Setting to 1.0 gives the suggestions a big promotion. + However, it does not necessarily mean that the top result + will be a boosted suggestion. + + Setting to -1.0 gives the suggestions a big demotion. + However, other suggestions that are relevant might still be + shown. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs: MutableSequence[ + "AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec", + ) + + completion_config: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + query_model: str = proto.Field( + proto.STRING, + number=3, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=4, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=9, + message=common.UserInfo, + ) + include_tail_suggestions: bool = proto.Field( + proto.BOOL, + number=5, + ) + boost_spec: BoostSpec = proto.Field( + proto.MESSAGE, + number=6, + message=BoostSpec, + ) + suggestion_types: MutableSequence[SuggestionType] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=SuggestionType, + ) + + +class AdvancedCompleteQueryResponse(proto.Message): + r"""Response message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. + + Attributes: + query_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.QuerySuggestion]): + Results of the matched query suggestions. The + result list is ordered and the first result is a + top suggestion. + tail_match_triggered (bool): + True if the returned suggestions are all tail suggestions. + + For tail matching to be triggered, include_tail_suggestions + in the request must be true and there must be no suggestions + that match the full query. + people_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.PersonSuggestion]): + Results of the matched people suggestions. + The result list is ordered and the first result + is the top suggestion. + content_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.ContentSuggestion]): + Results of the matched content suggestions. + The result list is ordered and the first result + is the top suggestion. + recent_search_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.RecentSearchSuggestion]): + Results of the matched "recent search" + suggestions. The result list is ordered and the + first result is the top suggestion. + """ + + class QuerySuggestion(proto.Message): + r"""Suggestions as search queries. + + Attributes: + suggestion (str): + The suggestion for the query. + completable_field_paths (MutableSequence[str]): + The unique document field paths that serve as + the source of this suggestion if it was + generated from completable fields. + + This field is only populated for the + document-completable model. + data_store (MutableSequence[str]): + The name of the dataStore that this + suggestion belongs to. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + completable_field_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + data_store: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class PersonSuggestion(proto.Message): + r"""Suggestions as people. + + Attributes: + suggestion (str): + The suggestion for the query. + person_type (google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.PersonSuggestion.PersonType): + The type of the person. + document (google.cloud.discoveryengine_v1beta.types.Document): + The document data snippet in the suggestion. + Only a subset of fields is populated. + data_store (str): + The name of the dataStore that this + suggestion belongs to. + """ + + class PersonType(proto.Enum): + r"""The type of the person based on the source. + + Values: + PERSON_TYPE_UNSPECIFIED (0): + Default value. + CLOUD_IDENTITY (1): + The suggestion is from a GOOGLE_IDENTITY source. + THIRD_PARTY_IDENTITY (2): + The suggestion is from a THIRD_PARTY_IDENTITY source. + """ + PERSON_TYPE_UNSPECIFIED = 0 + CLOUD_IDENTITY = 1 + THIRD_PARTY_IDENTITY = 2 + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + person_type: "AdvancedCompleteQueryResponse.PersonSuggestion.PersonType" = ( + proto.Field( + proto.ENUM, + number=2, + enum="AdvancedCompleteQueryResponse.PersonSuggestion.PersonType", + ) + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_document.Document, + ) + data_store: str = proto.Field( + proto.STRING, + number=5, + ) + + class ContentSuggestion(proto.Message): + r"""Suggestions as content. + + Attributes: + suggestion (str): + The suggestion for the query. + content_type (google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.ContentSuggestion.ContentType): + The type of the content suggestion. + document (google.cloud.discoveryengine_v1beta.types.Document): + The document data snippet in the suggestion. + Only a subset of fields will be populated. + data_store (str): + The name of the dataStore that this + suggestion belongs to. + """ + + class ContentType(proto.Enum): + r"""The type of the content returned for content suggestions. + + Values: + CONTENT_TYPE_UNSPECIFIED (0): + Default value. + GOOGLE_WORKSPACE (1): + The suggestion is from a Google Workspace + source. + THIRD_PARTY (2): + The suggestion is from a third party source. + """ + CONTENT_TYPE_UNSPECIFIED = 0 + GOOGLE_WORKSPACE = 1 + THIRD_PARTY = 2 + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + content_type: "AdvancedCompleteQueryResponse.ContentSuggestion.ContentType" = ( + proto.Field( + proto.ENUM, + number=2, + enum="AdvancedCompleteQueryResponse.ContentSuggestion.ContentType", + ) + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_document.Document, + ) + data_store: str = proto.Field( + proto.STRING, + number=5, + ) + + class RecentSearchSuggestion(proto.Message): + r"""Suggestions from recent search history. + + Attributes: + suggestion (str): + The suggestion for the query. + recent_search_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this recent rearch happened. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + recent_search_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QuerySuggestion, + ) + tail_match_triggered: bool = proto.Field( + proto.BOOL, + number=2, + ) + people_suggestions: MutableSequence[PersonSuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=PersonSuggestion, + ) + content_suggestions: MutableSequence[ContentSuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=ContentSuggestion, + ) + recent_search_suggestions: MutableSequence[ + RecentSearchSuggestion + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=RecentSearchSuggestion, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/control.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/control.py new file mode 100644 index 0000000000000000000000000000000000000000..18f25131440746fa64de2dab3f11b130fff05a6d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/control.py @@ -0,0 +1,345 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Condition", + "Control", + }, +) + + +class Condition(proto.Message): + r"""Defines circumstances to be checked before allowing a + behavior + + Attributes: + query_terms (MutableSequence[google.cloud.discoveryengine_v1beta.types.Condition.QueryTerm]): + Search only A list of terms to match the query on. Cannot be + set when + [Condition.query_regex][google.cloud.discoveryengine.v1beta.Condition.query_regex] + is set. + + Maximum of 10 query terms. + active_time_range (MutableSequence[google.cloud.discoveryengine_v1beta.types.Condition.TimeRange]): + Range of time(s) specifying when condition is + active. + Maximum of 10 time ranges. + query_regex (str): + Optional. Query regex to match the whole search query. + Cannot be set when + [Condition.query_terms][google.cloud.discoveryengine.v1beta.Condition.query_terms] + is set. This is currently supporting promotion use case. + """ + + class QueryTerm(proto.Message): + r"""Matcher for search request query + + Attributes: + value (str): + The specific query value to match against + + Must be lowercase, must be UTF-8. Can have at most 3 space + separated terms if full_match is true. Cannot be an empty + string. Maximum length of 5000 characters. + full_match (bool): + Whether the search query needs to exactly + match the query term. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + full_match: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class TimeRange(proto.Message): + r"""Used for time-dependent conditions. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time range. + + Range is inclusive. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time range. + + Range is inclusive. + Must be in the future. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_terms: MutableSequence[QueryTerm] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=QueryTerm, + ) + active_time_range: MutableSequence[TimeRange] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TimeRange, + ) + query_regex: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Control(proto.Message): + r"""Defines a conditioned behavior to employ during serving. Must be + attached to a + [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig] + to be considered at serving time. Permitted actions dependent on + ``SolutionType``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + boost_action (google.cloud.discoveryengine_v1beta.types.Control.BoostAction): + Defines a boost-type control + + This field is a member of `oneof`_ ``action``. + filter_action (google.cloud.discoveryengine_v1beta.types.Control.FilterAction): + Defines a filter-type control + Currently not supported by Recommendation + + This field is a member of `oneof`_ ``action``. + redirect_action (google.cloud.discoveryengine_v1beta.types.Control.RedirectAction): + Defines a redirect-type control. + + This field is a member of `oneof`_ ``action``. + synonyms_action (google.cloud.discoveryengine_v1beta.types.Control.SynonymsAction): + Treats a group of terms as synonyms of one + another. + + This field is a member of `oneof`_ ``action``. + name (str): + Immutable. Fully qualified name + ``projects/*/locations/global/dataStore/*/controls/*`` + display_name (str): + Required. Human readable name. The identifier + used in UI views. + Must be UTF-8 encoded string. Length limit is + 128 characters. Otherwise an INVALID ARGUMENT + error is thrown. + associated_serving_config_ids (MutableSequence[str]): + Output only. List of all + [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig] + IDs this control is attached to. May take up to 10 minutes + to update after changes. + solution_type (google.cloud.discoveryengine_v1beta.types.SolutionType): + Required. Immutable. What solution the + control belongs to. + Must be compatible with vertical of resource. + Otherwise an INVALID ARGUMENT error is thrown. + use_cases (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchUseCase]): + Specifies the use case for the control. Affects what + condition fields can be set. Only applies to + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + Currently only allow one use case per control. Must be set + when solution_type is + [SolutionType.SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + conditions (MutableSequence[google.cloud.discoveryengine_v1beta.types.Condition]): + Determines when the associated action will + trigger. + Omit to always apply the action. + Currently only a single condition may be + specified. Otherwise an INVALID ARGUMENT error + is thrown. + """ + + class BoostAction(proto.Message): + r"""Adjusts order of products in returned list. + + Attributes: + boost (float): + Required. Strength of the boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0 (No-op). + filter (str): + Required. Specifies which products to apply + the boost to. + If no filter is provided all products will be + boosted (No-op). Syntax documentation: + + https://cloud.google.com/retail/docs/filter-and-order + Maximum length is 5000 characters. + Otherwise an INVALID ARGUMENT error is thrown. + data_store (str): + Required. Specifies which data store's documents can be + boosted by this control. Full data store name e.g. + projects/123/locations/global/collections/default_collection/dataStores/default_data_store + """ + + boost: float = proto.Field( + proto.FLOAT, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + data_store: str = proto.Field( + proto.STRING, + number=3, + ) + + class FilterAction(proto.Message): + r"""Specified which products may be included in results. + Uses same filter as boost. + + Attributes: + filter (str): + Required. A filter to apply on the matching + condition results. + Required + Syntax documentation: + + https://cloud.google.com/retail/docs/filter-and-order + Maximum length is 5000 characters. Otherwise an + INVALID ARGUMENT error is thrown. + data_store (str): + Required. Specifies which data store's documents can be + filtered by this control. Full data store name e.g. + projects/123/locations/global/collections/default_collection/dataStores/default_data_store + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + data_store: str = proto.Field( + proto.STRING, + number=2, + ) + + class RedirectAction(proto.Message): + r"""Redirects a shopper to the provided URI. + + Attributes: + redirect_uri (str): + Required. The URI to which the shopper will + be redirected. + Required. + URI must have length equal or less than 2000 + characters. Otherwise an INVALID ARGUMENT error + is thrown. + """ + + redirect_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class SynonymsAction(proto.Message): + r"""Creates a set of terms that will act as synonyms of one + another. + Example: "happy" will also be considered as "glad", "glad" will + also be considered as "happy". + + Attributes: + synonyms (MutableSequence[str]): + Defines a set of synonyms. + Can specify up to 100 synonyms. + Must specify at least 2 synonyms. Otherwise an + INVALID ARGUMENT error is thrown. + """ + + synonyms: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + boost_action: BoostAction = proto.Field( + proto.MESSAGE, + number=6, + oneof="action", + message=BoostAction, + ) + filter_action: FilterAction = proto.Field( + proto.MESSAGE, + number=7, + oneof="action", + message=FilterAction, + ) + redirect_action: RedirectAction = proto.Field( + proto.MESSAGE, + number=9, + oneof="action", + message=RedirectAction, + ) + synonyms_action: SynonymsAction = proto.Field( + proto.MESSAGE, + number=10, + oneof="action", + message=SynonymsAction, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + associated_serving_config_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + solution_type: common.SolutionType = proto.Field( + proto.ENUM, + number=4, + enum=common.SolutionType, + ) + use_cases: MutableSequence[common.SearchUseCase] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=common.SearchUseCase, + ) + conditions: MutableSequence["Condition"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Condition", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/control_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/control_service.py new file mode 100644 index 0000000000000000000000000000000000000000..0f75538cf8efea9270e00c91df28ef0c6abf5f34 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/control_service.py @@ -0,0 +1,202 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import control as gcd_control + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "CreateControlRequest", + "UpdateControlRequest", + "DeleteControlRequest", + "GetControlRequest", + "ListControlsRequest", + "ListControlsResponse", + }, +) + + +class CreateControlRequest(proto.Message): + r"""Request for CreateControl method. + + Attributes: + parent (str): + Required. Full resource name of parent data store. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` + or + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + control (google.cloud.discoveryengine_v1beta.types.Control): + Required. The Control to create. + control_id (str): + Required. The ID to use for the Control, which will become + the final component of the Control's resource name. + + This value must be within 1-63 characters. Valid characters + are /[a-z][0-9]-\_/. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + control: gcd_control.Control = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_control.Control, + ) + control_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateControlRequest(proto.Message): + r"""Request for UpdateControl method. + + Attributes: + control (google.cloud.discoveryengine_v1beta.types.Control): + Required. The Control to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Indicates which fields in the provided + [Control][google.cloud.discoveryengine.v1beta.Control] to + update. The following are NOT supported: + + - [Control.name][google.cloud.discoveryengine.v1beta.Control.name] + - [Control.solution_type][google.cloud.discoveryengine.v1beta.Control.solution_type] + + If not set or empty, all supported fields are updated. + """ + + control: gcd_control.Control = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_control.Control, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteControlRequest(proto.Message): + r"""Request for DeleteControl method. + + Attributes: + name (str): + Required. The resource name of the Control to delete. + Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetControlRequest(proto.Message): + r"""Request for GetControl method. + + Attributes: + name (str): + Required. The resource name of the Control to get. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListControlsRequest(proto.Message): + r"""Request for ListControls method. + + Attributes: + parent (str): + Required. The data store resource name. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` + or + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 50. Max + allowed value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListControls`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. A filter to apply on the list results. Supported + features: + + - List all the products under the parent branch if + [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] + is unset. Currently this field is unsupported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListControlsResponse(proto.Message): + r"""Response for ListControls method. + + Attributes: + controls (MutableSequence[google.cloud.discoveryengine_v1beta.types.Control]): + All the Controls for a given data store. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + controls: MutableSequence[gcd_control.Control] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_control.Control, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/conversation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/conversation.py new file mode 100644 index 0000000000000000000000000000000000000000..55405fdd47db6f5a51acd3d596fad3f7e1d0f43a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/conversation.py @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Conversation", + "Reply", + "ConversationContext", + "TextInput", + "ConversationMessage", + }, +) + + +class Conversation(proto.Message): + r"""External conversation proto definition. + + Attributes: + name (str): + Immutable. Fully qualified name + ``projects/{project}/locations/global/collections/{collection}/dataStore/*/conversations/*`` + or + ``projects/{project}/locations/global/collections/{collection}/engines/*/conversations/*``. + state (google.cloud.discoveryengine_v1beta.types.Conversation.State): + The state of the Conversation. + user_pseudo_id (str): + A unique identifier for tracking users. + messages (MutableSequence[google.cloud.discoveryengine_v1beta.types.ConversationMessage]): + Conversation messages. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + finished. + """ + + class State(proto.Enum): + r"""Enumeration of the state of the conversation. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + IN_PROGRESS (1): + Conversation is currently open. + COMPLETED (2): + Conversation has been completed. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + COMPLETED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=3, + ) + messages: MutableSequence["ConversationMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="ConversationMessage", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class Reply(proto.Message): + r"""Defines a reply message to user. + + Attributes: + reply (str): + DEPRECATED: use ``summary`` instead. Text reply. + references (MutableSequence[google.cloud.discoveryengine_v1beta.types.Reply.Reference]): + References in the reply. + summary (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary): + Summary based on search results. + """ + + class Reference(proto.Message): + r"""Defines reference in reply. + + Attributes: + uri (str): + URI link reference. + anchor_text (str): + Anchor text. + start (int): + Anchor text start index. + end (int): + Anchor text end index. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + anchor_text: str = proto.Field( + proto.STRING, + number=2, + ) + start: int = proto.Field( + proto.INT32, + number=3, + ) + end: int = proto.Field( + proto.INT32, + number=4, + ) + + reply: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence[Reference] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Reference, + ) + summary: search_service.SearchResponse.Summary = proto.Field( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.Summary, + ) + + +class ConversationContext(proto.Message): + r"""Defines context of the conversation + + Attributes: + context_documents (MutableSequence[str]): + The current list of documents the user is + seeing. It contains the document resource + references. + active_document (str): + The current active document the user opened. + It contains the document resource reference. + """ + + context_documents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + active_document: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TextInput(proto.Message): + r"""Defines text input. + + Attributes: + input (str): + Text input. + context (google.cloud.discoveryengine_v1beta.types.ConversationContext): + Conversation context of the input. + """ + + input: str = proto.Field( + proto.STRING, + number=1, + ) + context: "ConversationContext" = proto.Field( + proto.MESSAGE, + number=2, + message="ConversationContext", + ) + + +class ConversationMessage(proto.Message): + r"""Defines a conversation message. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_input (google.cloud.discoveryengine_v1beta.types.TextInput): + User text input. + + This field is a member of `oneof`_ ``message``. + reply (google.cloud.discoveryengine_v1beta.types.Reply): + Search reply. + + This field is a member of `oneof`_ ``message``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Message creation timestamp. + """ + + user_input: "TextInput" = proto.Field( + proto.MESSAGE, + number=1, + oneof="message", + message="TextInput", + ) + reply: "Reply" = proto.Field( + proto.MESSAGE, + number=2, + oneof="message", + message="Reply", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py new file mode 100644 index 0000000000000000000000000000000000000000..17b66604760fd55d7f80bbffec14c0ea86f1f834 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py @@ -0,0 +1,1388 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import answer as gcd_answer +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.discoveryengine_v1beta.types import session as gcd_session + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "ConverseConversationRequest", + "ConverseConversationResponse", + "CreateConversationRequest", + "UpdateConversationRequest", + "DeleteConversationRequest", + "GetConversationRequest", + "ListConversationsRequest", + "ListConversationsResponse", + "AnswerQueryRequest", + "AnswerQueryResponse", + "GetAnswerRequest", + "CreateSessionRequest", + "UpdateSessionRequest", + "DeleteSessionRequest", + "GetSessionRequest", + "ListSessionsRequest", + "ListSessionsResponse", + }, +) + + +class ConverseConversationRequest(proto.Message): + r"""Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically creates a + new conversation inside a ConverseConversation session. + query (google.cloud.discoveryengine_v1beta.types.TextInput): + Required. Current user input. + serving_config (str): + The resource name of the Serving Config to use. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` + If this is not set, the default serving config will be used. + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + The conversation to be used by auto session + only. The name field will be ignored as we + automatically assign new name for the + conversation in auto session. + safe_search (bool): + Whether to turn on safe search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec): + A specification for configuring the summary + returned in the response. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. Filter expression is + case-sensitive. This will be used to filter search results + which may affect the summary response. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + + Filtering in Vertex AI Search is done by mapping the LHS + filter key to a key property defined in the Vertex AI Search + backend -- this mapping is defined by the customer in their + schema. For example a media customer might have a field + 'name' in their schema. In this case the filter would look + like this: filter --> name:'ANY("king kong")' + + For more information about filtering including syntax and + filter operators, see + `Filter `__ + boost_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain documents in search + results which may affect the converse response. For more + information on boosting, see + `Boosting `__ + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query: gcd_conversation.TextInput = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.TextInput, + ) + serving_config: str = proto.Field( + proto.STRING, + number=3, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_conversation.Conversation, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=6, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = ( + proto.Field( + proto.MESSAGE, + number=8, + message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, + ) + ) + filter: str = proto.Field( + proto.STRING, + number=9, + ) + boost_spec: search_service.SearchRequest.BoostSpec = proto.Field( + proto.MESSAGE, + number=10, + message=search_service.SearchRequest.BoostSpec, + ) + + +class ConverseConversationResponse(proto.Message): + r"""Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + reply (google.cloud.discoveryengine_v1beta.types.Reply): + Answer to the current query. + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Updated conversation including the answer. + related_questions (MutableSequence[str]): + Suggested related questions. + search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): + Search Results. + """ + + reply: gcd_conversation.Reply = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Reply, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + related_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + search_results: MutableSequence[ + search_service.SearchResponse.SearchResult + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.SearchResult, + ) + + +class CreateConversationRequest(proto.Message): + r"""Request for CreateConversation method. + + Attributes: + parent (str): + Required. Full resource name of parent data store. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Required. The conversation to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + + +class UpdateConversationRequest(proto.Message): + r"""Request for UpdateConversation method. + + Attributes: + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Required. The Conversation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update. The following are NOT supported: + + - [Conversation.name][google.cloud.discoveryengine.v1beta.Conversation.name] + + If not set or empty, all supported fields are updated. + """ + + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversationRequest(proto.Message): + r"""Request for DeleteConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to delete. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetConversationRequest(proto.Message): + r"""Request for GetConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversationsRequest(proto.Message): + r"""Request for ListConversations method. + + Attributes: + parent (str): + Required. The data store resource name. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + page_size (int): + Maximum number of results to return. If + unspecified, defaults to 50. Max allowed value + is 1000. + page_token (str): + A page token, received from a previous ``ListConversations`` + call. Provide this to retrieve the subsequent page. + filter (str): + A filter to apply on the list results. The supported + features are: user_pseudo_id, state. + + Example: "user_pseudo_id = some_id". + order_by (str): + A comma-separated list of fields to order by, sorted in + ascending order. Use "desc" after a field name for + descending. Supported fields: + + - ``update_time`` + - ``create_time`` + - ``conversation_name`` + + Example: "update_time desc" "create_time". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListConversationsResponse(proto.Message): + r"""Response for ListConversations method. + + Attributes: + conversations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Conversation]): + All the Conversations for a given data store. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AnswerQueryRequest(proto.Message): + r"""Request message for + [ConversationalSearchService.AnswerQuery][google.cloud.discoveryengine.v1beta.ConversationalSearchService.AnswerQuery] + method. + + Attributes: + serving_config (str): + Required. The resource name of the Search serving config, + such as + ``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config``, + or + ``projects/*/locations/global/collections/default_collection/dataStores/*/servingConfigs/default_serving_config``. + This field is used to identify the serving configuration + name, set of models used to make the search. + query (google.cloud.discoveryengine_v1beta.types.Query): + Required. Current user query. + session (str): + The session resource name. Not required. + + When session field is not set, the API is in sessionless + mode. + + We support auto session mode: users can use the wildcard + symbol ``-`` as session ID. A new ID will be automatically + generated and assigned. + safety_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SafetySpec): + Model specification. + related_questions_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.RelatedQuestionsSpec): + Related questions specification. + grounding_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.GroundingSpec): + Optional. Grounding specification. + answer_generation_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.AnswerGenerationSpec): + Answer generation specification. + search_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec): + Search specification. + query_understanding_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.QueryUnderstandingSpec): + Query understanding specification. + asynchronous_mode (bool): + Deprecated: This field is deprecated. Streaming Answer API + will be supported. + + Asynchronous mode control. + + If enabled, the response will be returned with + answer/session resource name without final answer. The API + users need to do the polling to get the latest status of + answer/session by calling + [ConversationalSearchService.GetAnswer][google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetAnswer] + or + [ConversationalSearchService.GetSession][google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetSession] + method. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + class SafetySpec(proto.Message): + r"""Safety specification. + + Attributes: + enable (bool): + Enable the safety filtering on the answer + response. It is false by default. + """ + + enable: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class RelatedQuestionsSpec(proto.Message): + r"""Related questions specification. + + Attributes: + enable (bool): + Enable related questions feature if true. + """ + + enable: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class GroundingSpec(proto.Message): + r"""Grounding specification. + + Attributes: + include_grounding_supports (bool): + Optional. Specifies whether to include grounding_supports in + the answer. The default value is ``false``. + + When this field is set to ``true``, returned answer will + have ``grounding_score`` and will contain GroundingSupports + for each claim. + filtering_level (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.GroundingSpec.FilteringLevel): + Optional. Specifies whether to enable the + filtering based on grounding score and at what + level. + """ + + class FilteringLevel(proto.Enum): + r"""Level to filter based on answer grounding. + + Values: + FILTERING_LEVEL_UNSPECIFIED (0): + Default is no filter + FILTERING_LEVEL_LOW (1): + Filter answers based on a low threshold. + FILTERING_LEVEL_HIGH (2): + Filter answers based on a high threshold. + """ + FILTERING_LEVEL_UNSPECIFIED = 0 + FILTERING_LEVEL_LOW = 1 + FILTERING_LEVEL_HIGH = 2 + + include_grounding_supports: bool = proto.Field( + proto.BOOL, + number=2, + ) + filtering_level: "AnswerQueryRequest.GroundingSpec.FilteringLevel" = ( + proto.Field( + proto.ENUM, + number=3, + enum="AnswerQueryRequest.GroundingSpec.FilteringLevel", + ) + ) + + class AnswerGenerationSpec(proto.Message): + r"""Answer generation specification. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec): + Answer generation model specification. + prompt_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec): + Answer generation prompt specification. + include_citations (bool): + Specifies whether to include citation metadata in the + answer. The default value is ``false``. + answer_language_code (str): + Language code for Answer. Use language tags defined by + `BCP47 `__. + Note: This is an experimental feature. + ignore_adversarial_query (bool): + Specifies whether to filter out adversarial queries. The + default value is ``false``. + + Google employs search-query classification to detect + adversarial queries. No answer is returned if the search + query is classified as an adversarial query. For example, a + user might ask a question regarding negative comments about + the company or submit a query designed to generate unsafe, + policy-violating output. If this field is set to ``true``, + we skip generating answers for adversarial queries and + return fallback messages instead. + ignore_non_answer_seeking_query (bool): + Specifies whether to filter out queries that are not + answer-seeking. The default value is ``false``. + + Google employs search-query classification to detect + answer-seeking queries. No answer is returned if the search + query is classified as a non-answer seeking query. If this + field is set to ``true``, we skip generating answers for + non-answer seeking queries and return fallback messages + instead. + ignore_low_relevant_content (bool): + Specifies whether to filter out queries that have low + relevance. + + If this field is set to ``false``, all search results are + used regardless of relevance to generate answers. If set to + ``true`` or unset, the behavior will be determined + automatically by the service. + + This field is a member of `oneof`_ ``_ignore_low_relevant_content``. + ignore_jail_breaking_query (bool): + Optional. Specifies whether to filter out jail-breaking + queries. The default value is ``false``. + + Google employs search-query classification to detect + jail-breaking queries. No summary is returned if the search + query is classified as a jail-breaking query. A user might + add instructions to the query to change the tone, style, + language, content of the answer, or ask the model to act as + a different entity, e.g. "Reply in the tone of a competing + company's CEO". If this field is set to ``true``, we skip + generating summaries for jail-breaking queries and return + fallback messages instead. + """ + + class ModelSpec(proto.Message): + r"""Answer Generation Model specification. + + Attributes: + model_version (str): + Model version. If not set, it will use the + default stable model. Allowed values are: + stable, preview. + """ + + model_version: str = proto.Field( + proto.STRING, + number=1, + ) + + class PromptSpec(proto.Message): + r"""Answer generation prompt specification. + + Attributes: + preamble (str): + Customized preamble. + """ + + preamble: str = proto.Field( + proto.STRING, + number=1, + ) + + model_spec: "AnswerQueryRequest.AnswerGenerationSpec.ModelSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="AnswerQueryRequest.AnswerGenerationSpec.ModelSpec", + ) + prompt_spec: "AnswerQueryRequest.AnswerGenerationSpec.PromptSpec" = proto.Field( + proto.MESSAGE, + number=2, + message="AnswerQueryRequest.AnswerGenerationSpec.PromptSpec", + ) + include_citations: bool = proto.Field( + proto.BOOL, + number=3, + ) + answer_language_code: str = proto.Field( + proto.STRING, + number=4, + ) + ignore_adversarial_query: bool = proto.Field( + proto.BOOL, + number=5, + ) + ignore_non_answer_seeking_query: bool = proto.Field( + proto.BOOL, + number=6, + ) + ignore_low_relevant_content: bool = proto.Field( + proto.BOOL, + number=7, + optional=True, + ) + ignore_jail_breaking_query: bool = proto.Field( + proto.BOOL, + number=8, + ) + + class SearchSpec(proto.Message): + r"""Search specification. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_params (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchParams): + Search parameters. + + This field is a member of `oneof`_ ``input``. + search_result_list (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList): + Search result list. + + This field is a member of `oneof`_ ``input``. + """ + + class SearchParams(proto.Message): + r"""Search parameters. + + Attributes: + max_return_results (int): + Number of search results to return. + The default value is 10. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. Filter expression is + case-sensitive. This will be used to filter search results + which may affect the Answer response. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + + Filtering in Vertex AI Search is done by mapping the LHS + filter key to a key property defined in the Vertex AI Search + backend -- this mapping is defined by the customer in their + schema. For example a media customers might have a field + 'name' in their schema. In this case the filter would look + like this: filter --> name:'ANY("king kong")' + + For more information about filtering including syntax and + filter operators, see + `Filter `__ + boost_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain documents in search + results which may affect the answer query response. For more + information on boosting, see + `Boosting `__ + order_by (str): + The order in which documents are returned. Documents can be + ordered by a field in an + [Document][google.cloud.discoveryengine.v1beta.Document] + object. Leave it unset if ordered by relevance. ``order_by`` + expression is case-sensitive. For more information on + ordering, see + `Ordering `__ + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + search_result_mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SearchResultMode): + Specifies the search result mode. If unspecified, the search + result mode defaults to ``DOCUMENTS``. See `parse and chunk + documents `__ + data_store_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.DataStoreSpec]): + Specs defining dataStores to filter on in a + search call and configurations for those + dataStores. This is only considered for engines + with multiple dataStores use case. For single + dataStore within an engine, they should use the + specs at the top level. + natural_language_query_understanding_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec): + Optional. Specification to enable natural + language understanding capabilities for search + requests. + """ + + max_return_results: int = proto.Field( + proto.INT32, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + boost_spec: search_service.SearchRequest.BoostSpec = proto.Field( + proto.MESSAGE, + number=3, + message=search_service.SearchRequest.BoostSpec, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + search_result_mode: search_service.SearchRequest.ContentSearchSpec.SearchResultMode = proto.Field( + proto.ENUM, + number=5, + enum=search_service.SearchRequest.ContentSearchSpec.SearchResultMode, + ) + data_store_specs: MutableSequence[ + search_service.SearchRequest.DataStoreSpec + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=search_service.SearchRequest.DataStoreSpec, + ) + natural_language_query_understanding_spec: search_service.SearchRequest.NaturalLanguageQueryUnderstandingSpec = proto.Field( + proto.MESSAGE, + number=8, + message=search_service.SearchRequest.NaturalLanguageQueryUnderstandingSpec, + ) + + class SearchResultList(proto.Message): + r"""Search result list. + + Attributes: + search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult]): + Search results. + """ + + class SearchResult(proto.Message): + r"""Search result. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + unstructured_document_info (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo): + Unstructured document information. + + This field is a member of `oneof`_ ``content``. + chunk_info (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo): + Chunk information. + + This field is a member of `oneof`_ ``content``. + """ + + class UnstructuredDocumentInfo(proto.Message): + r"""Unstructured document information. + + Attributes: + document (str): + Document resource name. + uri (str): + URI for the document. + title (str): + Title. + document_contexts (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.DocumentContext]): + List of document contexts. The content will + be used for Answer Generation. This is supposed + to be the main content of the document that can + be long and comprehensive. + extractive_segments (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveSegment]): + List of extractive segments. + extractive_answers (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveAnswer]): + Deprecated: This field is deprecated and will have no effect + on the Answer generation. Please use document_contexts and + extractive_segments fields. List of extractive answers. + """ + + class DocumentContext(proto.Message): + r"""Document context. + + Attributes: + page_identifier (str): + Page identifier. + content (str): + Document content to be used for answer + generation. + """ + + page_identifier: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class ExtractiveSegment(proto.Message): + r"""Extractive segment. + `Guide `__ + Answer generation will only use it if document_contexts is empty. + This is supposed to be shorter snippets. + + Attributes: + page_identifier (str): + Page identifier. + content (str): + Extractive segment content. + """ + + page_identifier: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class ExtractiveAnswer(proto.Message): + r"""Extractive answer. + `Guide `__ + + Attributes: + page_identifier (str): + Page identifier. + content (str): + Extractive answer content. + """ + + page_identifier: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + document: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + document_contexts: MutableSequence[ + "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.DocumentContext" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.DocumentContext", + ) + extractive_segments: MutableSequence[ + "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveSegment" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveSegment", + ) + extractive_answers: MutableSequence[ + "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveAnswer" + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveAnswer", + ) + + class ChunkInfo(proto.Message): + r"""Chunk information. + + Attributes: + chunk (str): + Chunk resource name. + content (str): + Chunk textual content. + document_metadata (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo.DocumentMetadata): + Metadata of the document from the current + chunk. + """ + + class DocumentMetadata(proto.Message): + r"""Document metadata contains the information of the document of + the current chunk. + + Attributes: + uri (str): + Uri of the document. + title (str): + Title of the document. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + + chunk: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + document_metadata: "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo.DocumentMetadata" = proto.Field( + proto.MESSAGE, + number=4, + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo.DocumentMetadata", + ) + + unstructured_document_info: "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo" = proto.Field( + proto.MESSAGE, + number=1, + oneof="content", + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo", + ) + chunk_info: "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo" = proto.Field( + proto.MESSAGE, + number=2, + oneof="content", + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo", + ) + + search_results: MutableSequence[ + "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult", + ) + + search_params: "AnswerQueryRequest.SearchSpec.SearchParams" = proto.Field( + proto.MESSAGE, + number=1, + oneof="input", + message="AnswerQueryRequest.SearchSpec.SearchParams", + ) + search_result_list: "AnswerQueryRequest.SearchSpec.SearchResultList" = ( + proto.Field( + proto.MESSAGE, + number=2, + oneof="input", + message="AnswerQueryRequest.SearchSpec.SearchResultList", + ) + ) + + class QueryUnderstandingSpec(proto.Message): + r"""Query understanding specification. + + Attributes: + query_classification_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec): + Query classification specification. + query_rephraser_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec): + Query rephraser specification. + """ + + class QueryClassificationSpec(proto.Message): + r"""Query classification specification. + + Attributes: + types (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type]): + Enabled query classification types. + """ + + class Type(proto.Enum): + r"""Query classification types. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified query classification type. + ADVERSARIAL_QUERY (1): + Adversarial query classification type. + NON_ANSWER_SEEKING_QUERY (2): + Non-answer-seeking query classification type, + for chit chat. + JAIL_BREAKING_QUERY (3): + Jail-breaking query classification type. + NON_ANSWER_SEEKING_QUERY_V2 (4): + Non-answer-seeking query classification type, + for no clear intent. + """ + TYPE_UNSPECIFIED = 0 + ADVERSARIAL_QUERY = 1 + NON_ANSWER_SEEKING_QUERY = 2 + JAIL_BREAKING_QUERY = 3 + NON_ANSWER_SEEKING_QUERY_V2 = 4 + + types: MutableSequence[ + "AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type" + ] = proto.RepeatedField( + proto.ENUM, + number=1, + enum="AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type", + ) + + class QueryRephraserSpec(proto.Message): + r"""Query rephraser specification. + + Attributes: + disable (bool): + Disable query rephraser. + max_rephrase_steps (int): + Max rephrase steps. + The max number is 5 steps. + If not set or set to < 1, it will be set to 1 by + default. + """ + + disable: bool = proto.Field( + proto.BOOL, + number=1, + ) + max_rephrase_steps: int = proto.Field( + proto.INT32, + number=2, + ) + + query_classification_spec: "AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec", + ) + query_rephraser_spec: "AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec" = proto.Field( + proto.MESSAGE, + number=2, + message="AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec", + ) + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + query: gcd_session.Query = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.Query, + ) + session: str = proto.Field( + proto.STRING, + number=3, + ) + safety_spec: SafetySpec = proto.Field( + proto.MESSAGE, + number=4, + message=SafetySpec, + ) + related_questions_spec: RelatedQuestionsSpec = proto.Field( + proto.MESSAGE, + number=5, + message=RelatedQuestionsSpec, + ) + grounding_spec: GroundingSpec = proto.Field( + proto.MESSAGE, + number=6, + message=GroundingSpec, + ) + answer_generation_spec: AnswerGenerationSpec = proto.Field( + proto.MESSAGE, + number=7, + message=AnswerGenerationSpec, + ) + search_spec: SearchSpec = proto.Field( + proto.MESSAGE, + number=8, + message=SearchSpec, + ) + query_understanding_spec: QueryUnderstandingSpec = proto.Field( + proto.MESSAGE, + number=9, + message=QueryUnderstandingSpec, + ) + asynchronous_mode: bool = proto.Field( + proto.BOOL, + number=10, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=12, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + + +class AnswerQueryResponse(proto.Message): + r"""Response message for + [ConversationalSearchService.AnswerQuery][google.cloud.discoveryengine.v1beta.ConversationalSearchService.AnswerQuery] + method. + + Attributes: + answer (google.cloud.discoveryengine_v1beta.types.Answer): + Answer resource object. If + [AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec.max_rephrase_steps][google.cloud.discoveryengine.v1beta.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec.max_rephrase_steps] + is greater than 1, use + [Answer.name][google.cloud.discoveryengine.v1beta.Answer.name] + to fetch answer information using + [ConversationalSearchService.GetAnswer][google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetAnswer] + API. + session (google.cloud.discoveryengine_v1beta.types.Session): + Session resource object. It will be only available when + session field is set and valid in the + [AnswerQueryRequest][google.cloud.discoveryengine.v1beta.AnswerQueryRequest] + request. + answer_query_token (str): + A global unique ID used for logging. + """ + + answer: gcd_answer.Answer = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_answer.Answer, + ) + session: gcd_session.Session = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.Session, + ) + answer_query_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetAnswerRequest(proto.Message): + r"""Request for GetAnswer method. + + Attributes: + name (str): + Required. The resource name of the Answer to get. Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSessionRequest(proto.Message): + r"""Request for CreateSession method. + + Attributes: + parent (str): + Required. Full resource name of parent data store. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + session (google.cloud.discoveryengine_v1beta.types.Session): + Required. The session to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + session: gcd_session.Session = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.Session, + ) + + +class UpdateSessionRequest(proto.Message): + r"""Request for UpdateSession method. + + Attributes: + session (google.cloud.discoveryengine_v1beta.types.Session): + Required. The Session to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Session][google.cloud.discoveryengine.v1beta.Session] to + update. The following are NOT supported: + + - [Session.name][google.cloud.discoveryengine.v1beta.Session.name] + + If not set or empty, all supported fields are updated. + """ + + session: gcd_session.Session = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_session.Session, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSessionRequest(proto.Message): + r"""Request for DeleteSession method. + + Attributes: + name (str): + Required. The resource name of the Session to delete. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSessionRequest(proto.Message): + r"""Request for GetSession method. + + Attributes: + name (str): + Required. The resource name of the Session to get. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + include_answer_details (bool): + Optional. If set to true, the full session + including all answer details will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + include_answer_details: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListSessionsRequest(proto.Message): + r"""Request for ListSessions method. + + Attributes: + parent (str): + Required. The data store resource name. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` + page_size (int): + Maximum number of results to return. If + unspecified, defaults to 50. Max allowed value + is 1000. + page_token (str): + A page token, received from a previous ``ListSessions`` + call. Provide this to retrieve the subsequent page. + filter (str): + A comma-separated list of fields to filter by, in EBNF + grammar. The supported fields are: + + - ``user_pseudo_id`` + - ``state`` + - ``display_name`` + - ``starred`` + - ``is_pinned`` + - ``labels`` + - ``create_time`` + - ``update_time`` + + Examples: "user_pseudo_id = some_id" "display_name = + "some_name"" "starred = true" "is_pinned=true AND (NOT + labels:hidden)" "create_time > "1970-01-01T12:00:00Z"". + order_by (str): + A comma-separated list of fields to order by, sorted in + ascending order. Use "desc" after a field name for + descending. Supported fields: + + - ``update_time`` + - ``create_time`` + - ``session_name`` + - ``is_pinned`` + + Example: + + - "update_time desc" + - "create_time" + - "is_pinned desc,update_time desc": list sessions by + is_pinned first, then by update_time. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSessionsResponse(proto.Message): + r"""Response for ListSessions method. + + Attributes: + sessions (MutableSequence[google.cloud.discoveryengine_v1beta.types.Session]): + All the Sessions for a given data store. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + sessions: MutableSequence[gcd_session.Session] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_session.Session, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py new file mode 100644 index 0000000000000000000000000000000000000000..6f67d52fa25daaa4c5a6b25469d1da98ad380da3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "CustomTuningModel", + }, +) + + +class CustomTuningModel(proto.Message): + r"""Metadata that describes a custom tuned model. + + Attributes: + name (str): + Required. The fully qualified resource name of the model. + + Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/customTuningModels/{custom_tuning_model}``. + + Model must be an alpha-numerical string with limit of 40 + characters. + display_name (str): + The display name of the model. + model_version (int): + The version of the model. + model_state (google.cloud.discoveryengine_v1beta.types.CustomTuningModel.ModelState): + The state that the model is in (e.g.\ ``TRAINING`` or + ``TRAINING_FAILED``). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Deprecated: Timestamp the Model was created + at. + training_start_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp the model training was initiated. + metrics (MutableMapping[str, float]): + The metrics of the trained model. + error_message (str): + Currently this is only populated if the model state is + ``INPUT_VALIDATION_FAILED``. + """ + + class ModelState(proto.Enum): + r"""The state of the model. + + Values: + MODEL_STATE_UNSPECIFIED (0): + Default value. + TRAINING_PAUSED (1): + The model is in a paused training state. + TRAINING (2): + The model is currently training. + TRAINING_COMPLETE (3): + The model has successfully completed + training. + READY_FOR_SERVING (4): + The model is ready for serving. + TRAINING_FAILED (5): + The model training failed. + NO_IMPROVEMENT (6): + The model training finished successfully but + metrics did not improve. + INPUT_VALIDATION_FAILED (7): + Input data validation failed. Model training + didn't start. + """ + MODEL_STATE_UNSPECIFIED = 0 + TRAINING_PAUSED = 1 + TRAINING = 2 + TRAINING_COMPLETE = 3 + READY_FOR_SERVING = 4 + TRAINING_FAILED = 5 + NO_IMPROVEMENT = 6 + INPUT_VALIDATION_FAILED = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + model_version: int = proto.Field( + proto.INT64, + number=3, + ) + model_state: ModelState = proto.Field( + proto.ENUM, + number=4, + enum=ModelState, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + training_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + metrics: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=7, + ) + error_message: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/data_store.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/data_store.py new file mode 100644 index 0000000000000000000000000000000000000000..76f64b5352c7e6fbb2153c2690ea3f714d84fa47 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/data_store.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + document_processing_config as gcd_document_processing_config, +) +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import schema + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "DataStore", + "LanguageInfo", + "NaturalLanguageQueryUnderstandingConfig", + "WorkspaceConfig", + }, +) + + +class DataStore(proto.Message): + r"""DataStore captures global settings and configs at the + DataStore level. + + Attributes: + name (str): + Immutable. The full resource name of the data store. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + display_name (str): + Required. The data store display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + industry_vertical (google.cloud.discoveryengine_v1beta.types.IndustryVertical): + Immutable. The industry vertical that the + data store registers. + solution_types (MutableSequence[google.cloud.discoveryengine_v1beta.types.SolutionType]): + The solutions that the data store enrolls. Available + solutions for each + [industry_vertical][google.cloud.discoveryengine.v1beta.DataStore.industry_vertical]: + + - ``MEDIA``: ``SOLUTION_TYPE_RECOMMENDATION`` and + ``SOLUTION_TYPE_SEARCH``. + - ``SITE_SEARCH``: ``SOLUTION_TYPE_SEARCH`` is automatically + enrolled. Other solutions cannot be enrolled. + default_schema_id (str): + Output only. The id of the default + [Schema][google.cloud.discoveryengine.v1beta.Schema] + asscociated to this data store. + content_config (google.cloud.discoveryengine_v1beta.types.DataStore.ContentConfig): + Immutable. The content config of the data store. If this + field is unset, the server behavior defaults to + [ContentConfig.NO_CONTENT][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.NO_CONTENT]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + was created at. + language_info (google.cloud.discoveryengine_v1beta.types.LanguageInfo): + Language info for DataStore. + natural_language_query_understanding_config (google.cloud.discoveryengine_v1beta.types.NaturalLanguageQueryUnderstandingConfig): + Optional. Configuration for Natural Language + Query Understanding. + billing_estimation (google.cloud.discoveryengine_v1beta.types.DataStore.BillingEstimation): + Output only. Data size estimation for + billing. + workspace_config (google.cloud.discoveryengine_v1beta.types.WorkspaceConfig): + Config to store data store type configuration for workspace + data. This must be set when + [DataStore.content_config][google.cloud.discoveryengine.v1beta.DataStore.content_config] + is set as + [DataStore.ContentConfig.GOOGLE_WORKSPACE][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.GOOGLE_WORKSPACE]. + document_processing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig): + Configuration for Document understanding and + enrichment. + starting_schema (google.cloud.discoveryengine_v1beta.types.Schema): + The start schema to use for this + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + when provisioning it. If unset, a default vertical + specialized schema will be used. + + This field is only used by [CreateDataStore][] API, and will + be ignored if used in other APIs. This field will be omitted + from all API responses including [CreateDataStore][] API. To + retrieve a schema of a + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + use + [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] + API instead. + + The provided schema will be validated against certain rules + on schema. Learn more from `this + doc `__. + serving_config_data_store (google.cloud.discoveryengine_v1beta.types.DataStore.ServingConfigDataStore): + Optional. Stores serving config at DataStore + level. + """ + + class ContentConfig(proto.Enum): + r"""Content config of the data store. + + Values: + CONTENT_CONFIG_UNSPECIFIED (0): + Default value. + NO_CONTENT (1): + Only contains documents without any + [Document.content][google.cloud.discoveryengine.v1beta.Document.content]. + CONTENT_REQUIRED (2): + Only contains documents with + [Document.content][google.cloud.discoveryengine.v1beta.Document.content]. + PUBLIC_WEBSITE (3): + The data store is used for public website + search. + GOOGLE_WORKSPACE (4): + The data store is used for workspace search. Details of + workspace data store are specified in the + [WorkspaceConfig][google.cloud.discoveryengine.v1beta.WorkspaceConfig]. + """ + CONTENT_CONFIG_UNSPECIFIED = 0 + NO_CONTENT = 1 + CONTENT_REQUIRED = 2 + PUBLIC_WEBSITE = 3 + GOOGLE_WORKSPACE = 4 + + class BillingEstimation(proto.Message): + r"""Estimation of data size per data store. + + Attributes: + structured_data_size (int): + Data size for structured data in terms of + bytes. + unstructured_data_size (int): + Data size for unstructured data in terms of + bytes. + website_data_size (int): + Data size for websites in terms of bytes. + structured_data_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last updated timestamp for structured data. + unstructured_data_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last updated timestamp for unstructured data. + website_data_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last updated timestamp for websites. + """ + + structured_data_size: int = proto.Field( + proto.INT64, + number=1, + ) + unstructured_data_size: int = proto.Field( + proto.INT64, + number=2, + ) + website_data_size: int = proto.Field( + proto.INT64, + number=3, + ) + structured_data_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + unstructured_data_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + website_data_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + class ServingConfigDataStore(proto.Message): + r"""Stores information regarding the serving configurations at + DataStore level. + + Attributes: + disabled_for_serving (bool): + If set true, the DataStore will not be + available for serving search requests. + """ + + disabled_for_serving: bool = proto.Field( + proto.BOOL, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + industry_vertical: common.IndustryVertical = proto.Field( + proto.ENUM, + number=3, + enum=common.IndustryVertical, + ) + solution_types: MutableSequence[common.SolutionType] = proto.RepeatedField( + proto.ENUM, + number=5, + enum=common.SolutionType, + ) + default_schema_id: str = proto.Field( + proto.STRING, + number=7, + ) + content_config: ContentConfig = proto.Field( + proto.ENUM, + number=6, + enum=ContentConfig, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + language_info: "LanguageInfo" = proto.Field( + proto.MESSAGE, + number=14, + message="LanguageInfo", + ) + natural_language_query_understanding_config: "NaturalLanguageQueryUnderstandingConfig" = proto.Field( + proto.MESSAGE, + number=34, + message="NaturalLanguageQueryUnderstandingConfig", + ) + billing_estimation: BillingEstimation = proto.Field( + proto.MESSAGE, + number=23, + message=BillingEstimation, + ) + workspace_config: "WorkspaceConfig" = proto.Field( + proto.MESSAGE, + number=25, + message="WorkspaceConfig", + ) + document_processing_config: gcd_document_processing_config.DocumentProcessingConfig = proto.Field( + proto.MESSAGE, + number=27, + message=gcd_document_processing_config.DocumentProcessingConfig, + ) + starting_schema: schema.Schema = proto.Field( + proto.MESSAGE, + number=28, + message=schema.Schema, + ) + serving_config_data_store: ServingConfigDataStore = proto.Field( + proto.MESSAGE, + number=30, + message=ServingConfigDataStore, + ) + + +class LanguageInfo(proto.Message): + r"""Language info for DataStore. + + Attributes: + language_code (str): + The language code for the DataStore. + normalized_language_code (str): + Output only. This is the normalized form of language_code. + E.g.: language_code of ``en-GB``, ``en_GB``, ``en-UK`` or + ``en-gb`` will have normalized_language_code of ``en-GB``. + language (str): + Output only. Language part of normalized_language_code. + E.g.: ``en-US`` -> ``en``, ``zh-Hans-HK`` -> ``zh``, ``en`` + -> ``en``. + region (str): + Output only. Region part of normalized_language_code, if + present. E.g.: ``en-US`` -> ``US``, ``zh-Hans-HK`` -> + ``HK``, ``en`` -> \`\`. + """ + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + normalized_language_code: str = proto.Field( + proto.STRING, + number=2, + ) + language: str = proto.Field( + proto.STRING, + number=3, + ) + region: str = proto.Field( + proto.STRING, + number=4, + ) + + +class NaturalLanguageQueryUnderstandingConfig(proto.Message): + r"""Configuration for Natural Language Query Understanding. + + Attributes: + mode (google.cloud.discoveryengine_v1beta.types.NaturalLanguageQueryUnderstandingConfig.Mode): + Mode of Natural Language Query Understanding. If this field + is unset, the behavior defaults to + [NaturalLanguageQueryUnderstandingConfig.Mode.DISABLED][google.cloud.discoveryengine.v1beta.NaturalLanguageQueryUnderstandingConfig.Mode.DISABLED]. + """ + + class Mode(proto.Enum): + r"""Mode of Natural Language Query Understanding. When the + NaturalLanguageQueryUnderstandingConfig.Mode is ENABLED, the + natural language understanding capabilities will be enabled for + a search request if the + NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition + in the SearchRequest is ENABLED. + + Values: + MODE_UNSPECIFIED (0): + Default value. + DISABLED (1): + Natural Language Query Understanding is + disabled. + ENABLED (2): + Natural Language Query Understanding is + enabled. + """ + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + + +class WorkspaceConfig(proto.Message): + r"""Config to store data store type configuration for workspace + data + + Attributes: + type_ (google.cloud.discoveryengine_v1beta.types.WorkspaceConfig.Type): + The Google Workspace data source. + dasher_customer_id (str): + Obfuscated Dasher customer ID. + super_admin_service_account (str): + Optional. The super admin service account for + the workspace that will be used for access token + generation. For now we only use it for Native + Google Drive connector data ingestion. + super_admin_email_address (str): + Optional. The super admin email address for + the workspace that will be used for access token + generation. For now we only use it for Native + Google Drive connector data ingestion. + """ + + class Type(proto.Enum): + r"""Specifies the type of Workspace App supported by this + DataStore + + Values: + TYPE_UNSPECIFIED (0): + Defaults to an unspecified Workspace type. + GOOGLE_DRIVE (1): + Workspace Data Store contains Drive data + GOOGLE_MAIL (2): + Workspace Data Store contains Mail data + GOOGLE_SITES (3): + Workspace Data Store contains Sites data + GOOGLE_CALENDAR (4): + Workspace Data Store contains Calendar data + GOOGLE_CHAT (5): + Workspace Data Store contains Chat data + GOOGLE_GROUPS (6): + Workspace Data Store contains Groups data + GOOGLE_KEEP (7): + Workspace Data Store contains Keep data + """ + TYPE_UNSPECIFIED = 0 + GOOGLE_DRIVE = 1 + GOOGLE_MAIL = 2 + GOOGLE_SITES = 3 + GOOGLE_CALENDAR = 4 + GOOGLE_CHAT = 5 + GOOGLE_GROUPS = 6 + GOOGLE_KEEP = 7 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + dasher_customer_id: str = proto.Field( + proto.STRING, + number=2, + ) + super_admin_service_account: str = proto.Field( + proto.STRING, + number=4, + ) + super_admin_email_address: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/data_store_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/data_store_service.py new file mode 100644 index 0000000000000000000000000000000000000000..faf087d44736fe4b5f0296d28c5ec21cccdc4ac4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/data_store_service.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import data_store as gcd_data_store + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "CreateDataStoreRequest", + "GetDataStoreRequest", + "CreateDataStoreMetadata", + "ListDataStoresRequest", + "ListDataStoresResponse", + "DeleteDataStoreRequest", + "UpdateDataStoreRequest", + "DeleteDataStoreMetadata", + }, +) + + +class CreateDataStoreRequest(proto.Message): + r"""Request for + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1beta.DataStoreService.CreateDataStore] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + data_store (google.cloud.discoveryengine_v1beta.types.DataStore): + Required. The + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + to create. + data_store_id (str): + Required. The ID to use for the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + which will become the final component of the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]'s + resource name. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + create_advanced_site_search (bool): + A boolean flag indicating whether user want to directly + create an advanced data store for site search. If the data + store is not configured as site search (GENERIC vertical and + PUBLIC_WEBSITE content_config), this flag will be ignored. + skip_default_schema_creation (bool): + A boolean flag indicating whether to skip the default schema + creation for the data store. Only enable this flag if you + are certain that the default schema is incompatible with + your use case. + + If set to true, you must manually create a schema for the + data store before any documents can be ingested. + + This flag cannot be specified if + ``data_store.starting_schema`` is specified. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_store: gcd_data_store.DataStore = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_data_store.DataStore, + ) + data_store_id: str = proto.Field( + proto.STRING, + number=3, + ) + create_advanced_site_search: bool = proto.Field( + proto.BOOL, + number=4, + ) + skip_default_schema_creation: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class GetDataStoreRequest(proto.Message): + r"""Request message for + [DataStoreService.GetDataStore][google.cloud.discoveryengine.v1beta.DataStoreService.GetDataStore] + method. + + Attributes: + name (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to access the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDataStoreMetadata(proto.Message): + r"""Metadata related to the progress of the + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1beta.DataStoreService.CreateDataStore] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListDataStoresRequest(proto.Message): + r"""Request message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1beta.DataStoreService.ListDataStores] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + + If the caller does not have permission to list + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]s + under this location, regardless of whether or not this data + store exists, a PERMISSION_DENIED error is returned. + page_size (int): + Maximum number of + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]s + to return. If unspecified, defaults to 10. The maximum + allowed value is 50. Values above 50 will be coerced to 50. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListDataStoresResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListDataStoresResponse.next_page_token], + received from a previous + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1beta.DataStoreService.ListDataStores] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1beta.DataStoreService.ListDataStores] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + Filter by solution type . For example: + ``filter = 'solution_type:SOLUTION_TYPE_SEARCH'`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDataStoresResponse(proto.Message): + r"""Response message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1beta.DataStoreService.ListDataStores] + method. + + Attributes: + data_stores (MutableSequence[google.cloud.discoveryengine_v1beta.types.DataStore]): + All the customer's + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]s. + next_page_token (str): + A token that can be sent as + [ListDataStoresRequest.page_token][google.cloud.discoveryengine.v1beta.ListDataStoresRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + data_stores: MutableSequence[gcd_data_store.DataStore] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_data_store.DataStore, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteDataStoreRequest(proto.Message): + r"""Request message for + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1beta.DataStoreService.DeleteDataStore] + method. + + Attributes: + name (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to delete the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + to delete does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataStoreRequest(proto.Message): + r"""Request message for + [DataStoreService.UpdateDataStore][google.cloud.discoveryengine.v1beta.DataStoreService.UpdateDataStore] + method. + + Attributes: + data_store (google.cloud.discoveryengine_v1beta.types.DataStore): + Required. The + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + to update. + + If the caller does not have permission to update the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + to update does not exist, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + data_store: gcd_data_store.DataStore = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_data_store.DataStore, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDataStoreMetadata(proto.Message): + r"""Metadata related to the progress of the + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1beta.DataStoreService.DeleteDataStore] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document.py new file mode 100644 index 0000000000000000000000000000000000000000..d673a125fca2ffdc116ae66762579a1b403a5e94 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Document", + }, +) + + +class Document(proto.Message): + r"""Document captures all raw metadata information of items to be + recommended or searched. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + struct_data (google.protobuf.struct_pb2.Struct): + The structured JSON data for the document. It should conform + to the registered + [Schema][google.cloud.discoveryengine.v1beta.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + json_data (str): + The JSON string representation of the document. It should + conform to the registered + [Schema][google.cloud.discoveryengine.v1beta.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + name (str): + Immutable. The full resource name of the document. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + id (str): + Immutable. The identifier of the document. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + schema_id (str): + The identifier of the schema located in the + same data store. + content (google.cloud.discoveryengine_v1beta.types.Document.Content): + The unstructured data linked to this document. Content must + be set if this document is under a ``CONTENT_REQUIRED`` data + store. + parent_document_id (str): + The identifier of the parent document. Currently supports at + most two level document hierarchy. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + derived_struct_data (google.protobuf.struct_pb2.Struct): + Output only. This field is OUTPUT_ONLY. It contains derived + data that are not in the original input document. + index_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time the document was indexed. If this + field is set, the document could be returned in search + results. + + This field is OUTPUT_ONLY. If this field is not populated, + it means the document has never been indexed. + index_status (google.cloud.discoveryengine_v1beta.types.Document.IndexStatus): + Output only. The index status of the document. + + - If document is indexed successfully, the index_time field + is populated. + - Otherwise, if document is not indexed due to errors, the + error_samples field is populated. + - Otherwise, index_status is unset. + """ + + class Content(proto.Message): + r"""Unstructured data linked to this document. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + raw_bytes (bytes): + The content represented as a stream of bytes. The maximum + length is 1,000,000 bytes (1 MB / ~0.95 MiB). + + Note: As with all ``bytes`` fields, this field is + represented as pure binary in Protocol Buffers and + base64-encoded string in JSON. For example, + ``abc123!?$*&()'-=@~`` should be represented as + ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See + https://developers.google.com/protocol-buffers/docs/proto3#json. + + This field is a member of `oneof`_ ``content``. + uri (str): + The URI of the content. Only Cloud Storage URIs (e.g. + ``gs://bucket-name/path/to/file``) are supported. The + maximum file size is 2.5 MB for text-based formats, 200 MB + for other formats. + + This field is a member of `oneof`_ ``content``. + mime_type (str): + The MIME type of the content. Supported types: + + - ``application/pdf`` (PDF, only native PDFs are supported + for now) + - ``text/html`` (HTML) + - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` + (DOCX) + - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` + (PPTX) + - ``text/plain`` (TXT) + + See + https://www.iana.org/assignments/media-types/media-types.xhtml. + """ + + raw_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="content", + ) + uri: str = proto.Field( + proto.STRING, + number=3, + oneof="content", + ) + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + + class IndexStatus(proto.Message): + r"""Index status of the document. + + Attributes: + index_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the document was indexed. + If this field is populated, it means the + document has been indexed. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while indexing + the document. If this field is populated, the + document is not indexed due to errors. + """ + + index_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + oneof="data", + message=struct_pb2.Struct, + ) + json_data: str = proto.Field( + proto.STRING, + number=5, + oneof="data", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + content: Content = proto.Field( + proto.MESSAGE, + number=10, + message=Content, + ) + parent_document_id: str = proto.Field( + proto.STRING, + number=7, + ) + derived_struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + index_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + index_status: IndexStatus = proto.Field( + proto.MESSAGE, + number=15, + message=IndexStatus, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document_processing_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document_processing_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d5840f2ac08f7c780eee00e3fb90f95ccdeb11e7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document_processing_config.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "DocumentProcessingConfig", + }, +) + + +class DocumentProcessingConfig(proto.Message): + r"""A singleton resource of + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. If it's + empty when + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] is + created and + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] is set to + [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.CONTENT_REQUIRED], + the default parser will default to digital parser. + + Attributes: + name (str): + The full resource name of the Document Processing Config. + Format: + ``projects/*/locations/*/collections/*/dataStores/*/documentProcessingConfig``. + chunking_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ChunkingConfig): + Whether chunking mode is enabled. + default_parsing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig): + Configurations for default Document parser. + If not specified, we will configure it as + default DigitalParsingConfig, and the default + parsing config will be applied to all file types + for Document parsing. + parsing_config_overrides (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig]): + Map from file type to override the default parsing + configuration based on the file type. Supported keys: + + - ``pdf``: Override parsing config for PDF files, either + digital parsing, ocr parsing or layout parsing is + supported. + - ``html``: Override parsing config for HTML files, only + digital parsing and layout parsing are supported. + - ``docx``: Override parsing config for DOCX files, only + digital parsing and layout parsing are supported. + - ``pptx``: Override parsing config for PPTX files, only + digital parsing and layout parsing are supported. + - ``xlsm``: Override parsing config for XLSM files, only + digital parsing and layout parsing are supported. + - ``xlsx``: Override parsing config for XLSX files, only + digital parsing and layout parsing are supported. + """ + + class ChunkingConfig(proto.Message): + r"""Configuration for chunking config. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + layout_based_chunking_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ChunkingConfig.LayoutBasedChunkingConfig): + Configuration for the layout based chunking. + + This field is a member of `oneof`_ ``chunk_mode``. + """ + + class LayoutBasedChunkingConfig(proto.Message): + r"""Configuration for the layout based chunking. + + Attributes: + chunk_size (int): + The token size limit for each chunk. + + Supported values: 100-500 (inclusive). + Default value: 500. + include_ancestor_headings (bool): + Whether to include appending different levels + of headings to chunks from the middle of the + document to prevent context loss. + + Default value: False. + """ + + chunk_size: int = proto.Field( + proto.INT32, + number=1, + ) + include_ancestor_headings: bool = proto.Field( + proto.BOOL, + number=2, + ) + + layout_based_chunking_config: "DocumentProcessingConfig.ChunkingConfig.LayoutBasedChunkingConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="chunk_mode", + message="DocumentProcessingConfig.ChunkingConfig.LayoutBasedChunkingConfig", + ) + + class ParsingConfig(proto.Message): + r"""Related configurations applied to a specific type of document + parser. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + digital_parsing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig.DigitalParsingConfig): + Configurations applied to digital parser. + + This field is a member of `oneof`_ ``type_dedicated_config``. + ocr_parsing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig.OcrParsingConfig): + Configurations applied to OCR parser. + Currently it only applies to PDFs. + + This field is a member of `oneof`_ ``type_dedicated_config``. + layout_parsing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig.LayoutParsingConfig): + Configurations applied to layout parser. + + This field is a member of `oneof`_ ``type_dedicated_config``. + """ + + class DigitalParsingConfig(proto.Message): + r"""The digital parsing configurations for documents.""" + + class OcrParsingConfig(proto.Message): + r"""The OCR parsing configurations for documents. + + Attributes: + enhanced_document_elements (MutableSequence[str]): + [DEPRECATED] This field is deprecated. To use the additional + enhanced document elements processing, please switch to + ``layout_parsing_config``. + use_native_text (bool): + If true, will use native text instead of OCR + text on pages containing native text. + """ + + enhanced_document_elements: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + use_native_text: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class LayoutParsingConfig(proto.Message): + r"""The layout parsing configurations for documents.""" + + digital_parsing_config: "DocumentProcessingConfig.ParsingConfig.DigitalParsingConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="type_dedicated_config", + message="DocumentProcessingConfig.ParsingConfig.DigitalParsingConfig", + ) + ocr_parsing_config: "DocumentProcessingConfig.ParsingConfig.OcrParsingConfig" = proto.Field( + proto.MESSAGE, + number=2, + oneof="type_dedicated_config", + message="DocumentProcessingConfig.ParsingConfig.OcrParsingConfig", + ) + layout_parsing_config: "DocumentProcessingConfig.ParsingConfig.LayoutParsingConfig" = proto.Field( + proto.MESSAGE, + number=3, + oneof="type_dedicated_config", + message="DocumentProcessingConfig.ParsingConfig.LayoutParsingConfig", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + chunking_config: ChunkingConfig = proto.Field( + proto.MESSAGE, + number=3, + message=ChunkingConfig, + ) + default_parsing_config: ParsingConfig = proto.Field( + proto.MESSAGE, + number=4, + message=ParsingConfig, + ) + parsing_config_overrides: MutableMapping[str, ParsingConfig] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=ParsingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document_service.py new file mode 100644 index 0000000000000000000000000000000000000000..35a4e549e55b05991df6be9845a0ff90db1815d5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/document_service.py @@ -0,0 +1,491 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document as gcd_document + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetDocumentRequest", + "ListDocumentsRequest", + "ListDocumentsResponse", + "CreateDocumentRequest", + "UpdateDocumentRequest", + "DeleteDocumentRequest", + "BatchGetDocumentsMetadataRequest", + "BatchGetDocumentsMetadataResponse", + }, +) + + +class GetDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1beta.Document] + does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list documents + under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1beta.Document]s + under this branch, regardless of whether or not this branch + exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to + return. If unspecified, defaults to 100. The maximum allowed + value is 1000. Values above 1000 are set to 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListDocumentsResponse.next_page_token], + received from a previous + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Document]): + The + [Document][google.cloud.discoveryengine.v1beta.Document]s. + next_page_token (str): + A token that can be sent as + [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1beta.ListDocumentsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + document (google.cloud.discoveryengine_v1beta.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1beta.Document] to + create. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1beta.Document], + which becomes the final component of the + [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1beta.Document]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + document_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] + method. + + Attributes: + document (google.cloud.discoveryengine_v1beta.types.Document): + Required. The document to update/create. + + If the caller does not have permission to update the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1beta.Document] to + update does not exist and + [allow_missing][google.cloud.discoveryengine.v1beta.UpdateDocumentRequest.allow_missing] + is not set, a ``NOT_FOUND`` error is returned. + allow_missing (bool): + If set to ``true`` and the + [Document][google.cloud.discoveryengine.v1beta.Document] is + not found, a new + [Document][google.cloud.discoveryengine.v1beta.Document] is + be created. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'document' to update. If not set, by + default updates all fields. + """ + + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1beta.Document] to + delete does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetDocumentsMetadataRequest(proto.Message): + r"""Request message for + [DocumentService.BatchGetDocumentsMetadata][google.cloud.discoveryengine.v1beta.DocumentService.BatchGetDocumentsMetadata] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + matcher (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataRequest.Matcher): + Required. Matcher for the + [Document][google.cloud.discoveryengine.v1beta.Document]s. + """ + + class UrisMatcher(proto.Message): + r"""Matcher for the + [Document][google.cloud.discoveryengine.v1beta.Document]s by exact + uris. + + Attributes: + uris (MutableSequence[str]): + The exact URIs to match by. + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class FhirMatcher(proto.Message): + r"""Matcher for the + [Document][google.cloud.discoveryengine.v1beta.Document]s by FHIR + resource names. + + Attributes: + fhir_resources (MutableSequence[str]): + Required. The FHIR resources to match by. Format: + projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}/fhir/{resource_type}/{fhir_resource_id} + """ + + fhir_resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Matcher(proto.Message): + r"""Matcher for the + [Document][google.cloud.discoveryengine.v1beta.Document]s. Currently + supports matching by exact URIs. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uris_matcher (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataRequest.UrisMatcher): + Matcher by exact URIs. + + This field is a member of `oneof`_ ``matcher``. + fhir_matcher (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataRequest.FhirMatcher): + Matcher by FHIR resource names. + + This field is a member of `oneof`_ ``matcher``. + """ + + uris_matcher: "BatchGetDocumentsMetadataRequest.UrisMatcher" = proto.Field( + proto.MESSAGE, + number=1, + oneof="matcher", + message="BatchGetDocumentsMetadataRequest.UrisMatcher", + ) + fhir_matcher: "BatchGetDocumentsMetadataRequest.FhirMatcher" = proto.Field( + proto.MESSAGE, + number=2, + oneof="matcher", + message="BatchGetDocumentsMetadataRequest.FhirMatcher", + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + matcher: Matcher = proto.Field( + proto.MESSAGE, + number=2, + message=Matcher, + ) + + +class BatchGetDocumentsMetadataResponse(proto.Message): + r"""Response message for + [DocumentService.BatchGetDocumentsMetadata][google.cloud.discoveryengine.v1beta.DocumentService.BatchGetDocumentsMetadata] + method. + + Attributes: + documents_metadata (MutableSequence[google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataResponse.DocumentMetadata]): + The metadata of the + [Document][google.cloud.discoveryengine.v1beta.Document]s. + """ + + class State(proto.Enum): + r"""The state of the + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Values: + STATE_UNSPECIFIED (0): + Should never be set. + INDEXED (1): + The [Document][google.cloud.discoveryengine.v1beta.Document] + is indexed. + NOT_IN_TARGET_SITE (2): + The [Document][google.cloud.discoveryengine.v1beta.Document] + is not indexed because its URI is not in the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]. + NOT_IN_INDEX (3): + The [Document][google.cloud.discoveryengine.v1beta.Document] + is not indexed. + """ + STATE_UNSPECIFIED = 0 + INDEXED = 1 + NOT_IN_TARGET_SITE = 2 + NOT_IN_INDEX = 3 + + class DocumentMetadata(proto.Message): + r"""The metadata of a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Attributes: + matcher_value (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataResponse.DocumentMetadata.MatcherValue): + The value of the matcher that was used to match the + [Document][google.cloud.discoveryengine.v1beta.Document]. + state (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataResponse.State): + The state of the document. + last_refreshed_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of the last time the + [Document][google.cloud.discoveryengine.v1beta.Document] was + last indexed. + data_ingestion_source (str): + The data ingestion source of the + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Allowed values are: + + - ``batch``: Data ingested via Batch API, e.g., + ImportDocuments. + - ``streaming`` Data ingested via Streaming API, e.g., FHIR + streaming. + """ + + class MatcherValue(proto.Message): + r"""The value of the matcher that was used to match the + [Document][google.cloud.discoveryengine.v1beta.Document]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + If match by URI, the URI of the + [Document][google.cloud.discoveryengine.v1beta.Document]. + + This field is a member of `oneof`_ ``matcher_value``. + fhir_resource (str): + Format: + projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}/fhir/{resource_type}/{fhir_resource_id} + + This field is a member of `oneof`_ ``matcher_value``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof="matcher_value", + ) + fhir_resource: str = proto.Field( + proto.STRING, + number=2, + oneof="matcher_value", + ) + + matcher_value: "BatchGetDocumentsMetadataResponse.DocumentMetadata.MatcherValue" = proto.Field( + proto.MESSAGE, + number=2, + message="BatchGetDocumentsMetadataResponse.DocumentMetadata.MatcherValue", + ) + state: "BatchGetDocumentsMetadataResponse.State" = proto.Field( + proto.ENUM, + number=3, + enum="BatchGetDocumentsMetadataResponse.State", + ) + last_refreshed_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + data_ingestion_source: str = proto.Field( + proto.STRING, + number=5, + ) + + documents_metadata: MutableSequence[DocumentMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=DocumentMetadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/engine.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..ae9bd23a98af82b8ab3c920ae28e28284ad7bdfb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/engine.py @@ -0,0 +1,347 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Engine", + }, +) + + +class Engine(proto.Message): + r"""Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1beta.Engine]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + chat_engine_config (google.cloud.discoveryengine_v1beta.types.Engine.ChatEngineConfig): + Configurations for the Chat Engine. Only applicable if + [solution_type][google.cloud.discoveryengine.v1beta.Engine.solution_type] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_CHAT]. + + This field is a member of `oneof`_ ``engine_config``. + search_engine_config (google.cloud.discoveryengine_v1beta.types.Engine.SearchEngineConfig): + Configurations for the Search Engine. Only applicable if + [solution_type][google.cloud.discoveryengine.v1beta.Engine.solution_type] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + + This field is a member of `oneof`_ ``engine_config``. + chat_engine_metadata (google.cloud.discoveryengine_v1beta.types.Engine.ChatEngineMetadata): + Output only. Additional information of the Chat Engine. Only + applicable if + [solution_type][google.cloud.discoveryengine.v1beta.Engine.solution_type] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_CHAT]. + + This field is a member of `oneof`_ ``engine_metadata``. + name (str): + Immutable. The fully qualified resource name of the engine. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + + Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` + engine should be 1-63 characters, and valid characters are + /[a-z0-9][a-z0-9-\_]*/. Otherwise, an INVALID_ARGUMENT error + is returned. + display_name (str): + Required. The display name of the engine. + Should be human readable. UTF-8 encoded string + with limit of 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the Recommendation + Engine was created at. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the Recommendation + Engine was last updated. + data_store_ids (MutableSequence[str]): + The data stores associated with this engine. + + For + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH] + and + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + type of engines, they can only associate with at most one + data store. + + If + [solution_type][google.cloud.discoveryengine.v1beta.Engine.solution_type] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_CHAT], + multiple + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]s + in the same + [Collection][google.cloud.discoveryengine.v1beta.Collection] + can be associated here. + + Note that when used in + [CreateEngineRequest][google.cloud.discoveryengine.v1beta.CreateEngineRequest], + one DataStore id must be provided as the system will use it + for necessary initializations. + solution_type (google.cloud.discoveryengine_v1beta.types.SolutionType): + Required. The solutions of the engine. + industry_vertical (google.cloud.discoveryengine_v1beta.types.IndustryVertical): + The industry vertical that the engine registers. The + restriction of the Engine industry vertical is based on + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]: + If unspecified, default to ``GENERIC``. Vertical on Engine + has to match vertical of the DataStore linked to the engine. + common_config (google.cloud.discoveryengine_v1beta.types.Engine.CommonConfig): + Common config spec that specifies the + metadata of the engine. + disable_analytics (bool): + Optional. Whether to disable analytics for + searches performed on this engine. + """ + + class SearchEngineConfig(proto.Message): + r"""Configurations for a Search Engine. + + Attributes: + search_tier (google.cloud.discoveryengine_v1beta.types.SearchTier): + The search feature tier of this engine. + + Different tiers might have different pricing. To learn more, + check the pricing documentation. + + Defaults to + [SearchTier.SEARCH_TIER_STANDARD][google.cloud.discoveryengine.v1beta.SearchTier.SEARCH_TIER_STANDARD] + if not specified. + search_add_ons (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchAddOn]): + The add-on that this search engine enables. + """ + + search_tier: common.SearchTier = proto.Field( + proto.ENUM, + number=1, + enum=common.SearchTier, + ) + search_add_ons: MutableSequence[common.SearchAddOn] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=common.SearchAddOn, + ) + + class ChatEngineConfig(proto.Message): + r"""Configurations for a Chat Engine. + + Attributes: + agent_creation_config (google.cloud.discoveryengine_v1beta.types.Engine.ChatEngineConfig.AgentCreationConfig): + The configurationt generate the Dialogflow agent that is + associated to this Engine. + + Note that these configurations are one-time consumed by and + passed to Dialogflow service. It means they cannot be + retrieved using + [EngineService.GetEngine][google.cloud.discoveryengine.v1beta.EngineService.GetEngine] + or + [EngineService.ListEngines][google.cloud.discoveryengine.v1beta.EngineService.ListEngines] + API after engine creation. + dialogflow_agent_to_link (str): + The resource name of an exist Dialogflow agent to link to + this Chat Engine. Customers can either provide + ``agent_creation_config`` to create agent or provide an + agent name that links the agent with the Chat engine. + + Format: + ``projects//locations//agents/``. + + Note that the ``dialogflow_agent_to_link`` are one-time + consumed by and passed to Dialogflow service. It means they + cannot be retrieved using + [EngineService.GetEngine][google.cloud.discoveryengine.v1beta.EngineService.GetEngine] + or + [EngineService.ListEngines][google.cloud.discoveryengine.v1beta.EngineService.ListEngines] + API after engine creation. Use + [ChatEngineMetadata.dialogflow_agent][google.cloud.discoveryengine.v1beta.Engine.ChatEngineMetadata.dialogflow_agent] + for actual agent association after Engine is created. + """ + + class AgentCreationConfig(proto.Message): + r"""Configurations for generating a Dialogflow agent. + + Note that these configurations are one-time consumed by and passed + to Dialogflow service. It means they cannot be retrieved using + [EngineService.GetEngine][google.cloud.discoveryengine.v1beta.EngineService.GetEngine] + or + [EngineService.ListEngines][google.cloud.discoveryengine.v1beta.EngineService.ListEngines] + API after engine creation. + + Attributes: + business (str): + Name of the company, organization or other + entity that the agent represents. Used for + knowledge connector LLM prompt and for knowledge + search. + default_language_code (str): + Required. The default language of the agent as a language + tag. See `Language + Support `__ + for a list of the currently supported language codes. + time_zone (str): + Required. The time zone of the agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + location (str): + Agent location for Agent creation, supported + values: global/us/eu. If not provided, us Engine + will create Agent using us-central-1 by default; + eu Engine will create Agent using eu-west-1 by + default. + """ + + business: str = proto.Field( + proto.STRING, + number=1, + ) + default_language_code: str = proto.Field( + proto.STRING, + number=2, + ) + time_zone: str = proto.Field( + proto.STRING, + number=3, + ) + location: str = proto.Field( + proto.STRING, + number=4, + ) + + agent_creation_config: "Engine.ChatEngineConfig.AgentCreationConfig" = ( + proto.Field( + proto.MESSAGE, + number=1, + message="Engine.ChatEngineConfig.AgentCreationConfig", + ) + ) + dialogflow_agent_to_link: str = proto.Field( + proto.STRING, + number=2, + ) + + class CommonConfig(proto.Message): + r"""Common configurations for an Engine. + + Attributes: + company_name (str): + The name of the company, business or entity + that is associated with the engine. Setting this + may help improve LLM related features. + """ + + company_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class ChatEngineMetadata(proto.Message): + r"""Additional information of a Chat Engine. + Fields in this message are output only. + + Attributes: + dialogflow_agent (str): + The resource name of a Dialogflow agent, that this Chat + Engine refers to. + + Format: + ``projects//locations//agents/``. + """ + + dialogflow_agent: str = proto.Field( + proto.STRING, + number=1, + ) + + chat_engine_config: ChatEngineConfig = proto.Field( + proto.MESSAGE, + number=11, + oneof="engine_config", + message=ChatEngineConfig, + ) + search_engine_config: SearchEngineConfig = proto.Field( + proto.MESSAGE, + number=13, + oneof="engine_config", + message=SearchEngineConfig, + ) + chat_engine_metadata: ChatEngineMetadata = proto.Field( + proto.MESSAGE, + number=12, + oneof="engine_metadata", + message=ChatEngineMetadata, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + data_store_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_type: common.SolutionType = proto.Field( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + industry_vertical: common.IndustryVertical = proto.Field( + proto.ENUM, + number=16, + enum=common.IndustryVertical, + ) + common_config: CommonConfig = proto.Field( + proto.MESSAGE, + number=15, + message=CommonConfig, + ) + disable_analytics: bool = proto.Field( + proto.BOOL, + number=26, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/engine_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/engine_service.py new file mode 100644 index 0000000000000000000000000000000000000000..da3b04f82745d6de0f69c9c191c80570faf33b81 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/engine_service.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import engine as gcd_engine + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "CreateEngineRequest", + "CreateEngineMetadata", + "DeleteEngineRequest", + "DeleteEngineMetadata", + "GetEngineRequest", + "ListEnginesRequest", + "ListEnginesResponse", + "UpdateEngineRequest", + "PauseEngineRequest", + "ResumeEngineRequest", + "TuneEngineRequest", + "TuneEngineMetadata", + "TuneEngineResponse", + }, +) + + +class CreateEngineRequest(proto.Message): + r"""Request for + [EngineService.CreateEngine][google.cloud.discoveryengine.v1beta.EngineService.CreateEngine] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + engine (google.cloud.discoveryengine_v1beta.types.Engine): + Required. The + [Engine][google.cloud.discoveryengine.v1beta.Engine] to + create. + engine_id (str): + Required. The ID to use for the + [Engine][google.cloud.discoveryengine.v1beta.Engine], which + will become the final component of the + [Engine][google.cloud.discoveryengine.v1beta.Engine]'s + resource name. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + engine: gcd_engine.Engine = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_engine.Engine, + ) + engine_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateEngineMetadata(proto.Message): + r"""Metadata related to the progress of the + [EngineService.CreateEngine][google.cloud.discoveryengine.v1beta.EngineService.CreateEngine] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteEngineRequest(proto.Message): + r"""Request message for + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1beta.EngineService.DeleteEngine] + method. + + Attributes: + name (str): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1beta.Engine], such + as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + If the caller does not have permission to delete the + [Engine][google.cloud.discoveryengine.v1beta.Engine], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Engine][google.cloud.discoveryengine.v1beta.Engine] + to delete does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteEngineMetadata(proto.Message): + r"""Metadata related to the progress of the + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1beta.EngineService.DeleteEngine] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GetEngineRequest(proto.Message): + r"""Request message for + [EngineService.GetEngine][google.cloud.discoveryengine.v1beta.EngineService.GetEngine] + method. + + Attributes: + name (str): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1beta.Engine], such + as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEnginesRequest(proto.Message): + r"""Request message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1beta.EngineService.ListEngines] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + page_size (int): + Optional. Not supported. + page_token (str): + Optional. Not supported. + filter (str): + Optional. Filter by solution type. For example: + solution_type=SOLUTION_TYPE_SEARCH + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEnginesResponse(proto.Message): + r"""Response message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1beta.EngineService.ListEngines] + method. + + Attributes: + engines (MutableSequence[google.cloud.discoveryengine_v1beta.types.Engine]): + All the customer's + [Engine][google.cloud.discoveryengine.v1beta.Engine]s. + next_page_token (str): + Not supported. + """ + + @property + def raw_page(self): + return self + + engines: MutableSequence[gcd_engine.Engine] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_engine.Engine, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateEngineRequest(proto.Message): + r"""Request message for + [EngineService.UpdateEngine][google.cloud.discoveryengine.v1beta.EngineService.UpdateEngine] + method. + + Attributes: + engine (google.cloud.discoveryengine_v1beta.types.Engine): + Required. The + [Engine][google.cloud.discoveryengine.v1beta.Engine] to + update. + + If the caller does not have permission to update the + [Engine][google.cloud.discoveryengine.v1beta.Engine], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Engine][google.cloud.discoveryengine.v1beta.Engine] + to update does not exist, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Engine][google.cloud.discoveryengine.v1beta.Engine] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + engine: gcd_engine.Engine = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_engine.Engine, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class PauseEngineRequest(proto.Message): + r"""Request for pausing training of an engine. + + Attributes: + name (str): + Required. The name of the engine to pause. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ResumeEngineRequest(proto.Message): + r"""Request for resuming training of an engine. + + Attributes: + name (str): + Required. The name of the engine to resume. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TuneEngineRequest(proto.Message): + r"""Request to manually start a tuning process now (instead of + waiting for the periodically scheduled tuning to happen). + + Attributes: + name (str): + Required. The resource name of the engine to tune. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TuneEngineMetadata(proto.Message): + r"""Metadata associated with a tune operation. + + Attributes: + engine (str): + Required. The resource name of the engine that this tune + applies to. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` + """ + + engine: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TuneEngineResponse(proto.Message): + r"""Response associated with a tune operation.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/evaluation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..3eaa5a067c457895550742f9397dffff50de4caf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/evaluation.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Evaluation", + "QualityMetrics", + }, +) + + +class Evaluation(proto.Message): + r"""An evaluation is a single execution (or run) of an evaluation + process. It encapsulates the state of the evaluation and the + resulting data. + + Attributes: + name (str): + Identifier. The full resource name of the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + in the format of + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + evaluation_spec (google.cloud.discoveryengine_v1beta.types.Evaluation.EvaluationSpec): + Required. The specification of the + evaluation. + quality_metrics (google.cloud.discoveryengine_v1beta.types.QualityMetrics): + Output only. The metrics produced by the evaluation, + averaged across all + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + in the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Only populated when the evaluation's state is SUCCEEDED. + state (google.cloud.discoveryengine_v1beta.types.Evaluation.State): + Output only. The state of the evaluation. + error (google.rpc.status_pb2.Status): + Output only. The error that occurred during + evaluation. Only populated when the evaluation's + state is FAILED. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + was created at. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + was completed at. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + Output only. A sample of errors encountered + while processing the request. + """ + + class State(proto.Enum): + r"""Describes the state of an evaluation. + + Values: + STATE_UNSPECIFIED (0): + The evaluation is unspecified. + PENDING (1): + The service is preparing to run the + evaluation. + RUNNING (2): + The evaluation is in progress. + SUCCEEDED (3): + The evaluation completed successfully. + FAILED (4): + The evaluation failed. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCEEDED = 3 + FAILED = 4 + + class EvaluationSpec(proto.Message): + r"""Describes the specification of the evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_request (google.cloud.discoveryengine_v1beta.types.SearchRequest): + Required. The search request that is used to perform the + evaluation. + + Only the following fields within SearchRequest are + supported; if any other fields are provided, an UNSUPPORTED + error will be returned: + + - [SearchRequest.serving_config][google.cloud.discoveryengine.v1beta.SearchRequest.serving_config] + - [SearchRequest.branch][google.cloud.discoveryengine.v1beta.SearchRequest.branch] + - [SearchRequest.canonical_filter][google.cloud.discoveryengine.v1beta.SearchRequest.canonical_filter] + - [SearchRequest.query_expansion_spec][google.cloud.discoveryengine.v1beta.SearchRequest.query_expansion_spec] + - [SearchRequest.spell_correction_spec][google.cloud.discoveryengine.v1beta.SearchRequest.spell_correction_spec] + - [SearchRequest.content_search_spec][google.cloud.discoveryengine.v1beta.SearchRequest.content_search_spec] + - [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id] + + This field is a member of `oneof`_ ``search_spec``. + query_set_spec (google.cloud.discoveryengine_v1beta.types.Evaluation.EvaluationSpec.QuerySetSpec): + Required. The specification of the query set. + """ + + class QuerySetSpec(proto.Message): + r"""Describes the specification of the query set. + + Attributes: + sample_query_set (str): + Required. The full resource name of the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + used for the evaluation, in the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + """ + + sample_query_set: str = proto.Field( + proto.STRING, + number=1, + ) + + search_request: search_service.SearchRequest = proto.Field( + proto.MESSAGE, + number=2, + oneof="search_spec", + message=search_service.SearchRequest, + ) + query_set_spec: "Evaluation.EvaluationSpec.QuerySetSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="Evaluation.EvaluationSpec.QuerySetSpec", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_spec: EvaluationSpec = proto.Field( + proto.MESSAGE, + number=2, + message=EvaluationSpec, + ) + quality_metrics: "QualityMetrics" = proto.Field( + proto.MESSAGE, + number=3, + message="QualityMetrics", + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + message=status_pb2.Status, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=status_pb2.Status, + ) + + +class QualityMetrics(proto.Message): + r"""Describes the metrics produced by the evaluation. + + Attributes: + doc_recall (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Recall per document, at various top-k cutoff levels. + + Recall is the fraction of relevant documents retrieved out + of all relevant documents. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + If 3 out of 5 relevant documents are retrieved in the + top-5, recall@5 = 3/5 = 0.6 + doc_precision (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Precision per document, at various top-k cutoff levels. + + Precision is the fraction of retrieved documents that are + relevant. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + If 4 out of 5 retrieved documents in the top-5 are + relevant, precision@5 = 4/5 = 0.8 + doc_ndcg (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Normalized discounted cumulative gain (NDCG) per document, + at various top-k cutoff levels. + + NDCG measures the ranking quality, giving higher relevance + to top results. + + Example (top-3): Suppose + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + with three retrieved documents (D1, D2, D3) and binary + relevance judgements (1 for relevant, 0 for not relevant): + + Retrieved: [D3 (0), D1 (1), D2 (1)] Ideal: [D1 (1), D2 (1), + D3 (0)] + + Calculate NDCG@3 for each + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]: + \* DCG@3: 0/log2(1+1) + 1/log2(2+1) + 1/log2(3+1) = 1.13 \* + Ideal DCG@3: 1/log2(1+1) + 1/log2(2+1) + 0/log2(3+1) = 1.63 + \* NDCG@3: 1.13/1.63 = 0.693 + page_recall (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Recall per page, at various top-k cutoff levels. + + Recall is the fraction of relevant pages retrieved out of + all relevant pages. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + if 3 out of 5 relevant pages are retrieved in the top-5, + recall@5 = 3/5 = 0.6 + page_ndcg (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Normalized discounted cumulative gain (NDCG) per page, at + various top-k cutoff levels. + + NDCG measures the ranking quality, giving higher relevance + to top results. + + Example (top-3): Suppose + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + with three retrieved pages (P1, P2, P3) and binary relevance + judgements (1 for relevant, 0 for not relevant): + + Retrieved: [P3 (0), P1 (1), P2 (1)] Ideal: [P1 (1), P2 (1), + P3 (0)] + + Calculate NDCG@3 for + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]: + \* DCG@3: 0/log2(1+1) + 1/log2(2+1) + 1/log2(3+1) = 1.13 \* + Ideal DCG@3: 1/log2(1+1) + 1/log2(2+1) + 0/log2(3+1) = 1.63 + \* NDCG@3: 1.13/1.63 = 0.693 + """ + + class TopkMetrics(proto.Message): + r"""Stores the metric values at specific top-k levels. + + Attributes: + top_1 (float): + The top-1 value. + top_3 (float): + The top-3 value. + top_5 (float): + The top-5 value. + top_10 (float): + The top-10 value. + """ + + top_1: float = proto.Field( + proto.DOUBLE, + number=1, + ) + top_3: float = proto.Field( + proto.DOUBLE, + number=2, + ) + top_5: float = proto.Field( + proto.DOUBLE, + number=3, + ) + top_10: float = proto.Field( + proto.DOUBLE, + number=4, + ) + + doc_recall: TopkMetrics = proto.Field( + proto.MESSAGE, + number=1, + message=TopkMetrics, + ) + doc_precision: TopkMetrics = proto.Field( + proto.MESSAGE, + number=2, + message=TopkMetrics, + ) + doc_ndcg: TopkMetrics = proto.Field( + proto.MESSAGE, + number=3, + message=TopkMetrics, + ) + page_recall: TopkMetrics = proto.Field( + proto.MESSAGE, + number=4, + message=TopkMetrics, + ) + page_ndcg: TopkMetrics = proto.Field( + proto.MESSAGE, + number=5, + message=TopkMetrics, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/evaluation_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/evaluation_service.py new file mode 100644 index 0000000000000000000000000000000000000000..5f46e95ab5ac474d8355b62f366438ff922a95cf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/evaluation_service.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetEvaluationRequest", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "CreateEvaluationRequest", + "CreateEvaluationMetadata", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + }, +) + + +class GetEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation] + method. + + Attributes: + name (str): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + + Attributes: + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s + under this location, regardless of whether or not this + location exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s + to return. If unspecified, defaults to 100. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], + received from a previous + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEvaluationsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + + Attributes: + evaluations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Evaluation]): + The + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s. + next_page_token (str): + A token that can be sent as + [ListEvaluationsRequest.page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluations: MutableSequence[gcd_evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_evaluation.Evaluation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + evaluation (google.cloud.discoveryengine_v1beta.types.Evaluation): + Required. The + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation: gcd_evaluation.Evaluation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation.Evaluation, + ) + + +class CreateEvaluationMetadata(proto.Message): + r"""Metadata for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + + """ + + +class ListEvaluationResultsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + + Attributes: + evaluation (str): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless of + whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of [EvaluationResult][] to return. If + unspecified, defaults to 100. The maximum allowed value is + 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListEvaluationResultsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationResultsResponse.next_page_token], + received from a previous + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + evaluation: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEvaluationResultsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + + Attributes: + evaluation_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse.EvaluationResult]): + The + [EvaluationResult][google.cloud.discoveryengine.v1beta.ListEvaluationResultsResponse.EvaluationResult]s. + next_page_token (str): + A token that can be sent as + [ListEvaluationResultsRequest.page_token][google.cloud.discoveryengine.v1beta.ListEvaluationResultsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + class EvaluationResult(proto.Message): + r"""Represents the results of an evaluation for a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Attributes: + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Output only. The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + that was evaluated. + quality_metrics (google.cloud.discoveryengine_v1beta.types.QualityMetrics): + Output only. The metrics produced by the evaluation, for a + given + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + """ + + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + quality_metrics: gcd_evaluation.QualityMetrics = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation.QualityMetrics, + ) + + @property + def raw_page(self): + return self + + evaluation_results: MutableSequence[EvaluationResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=EvaluationResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py new file mode 100644 index 0000000000000000000000000000000000000000..e17521198310571ef9465b0b127c9cc40ff2c557 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py @@ -0,0 +1,942 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import grounding + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GroundedGenerationContent", + "GenerateGroundedContentRequest", + "GenerateGroundedContentResponse", + "CheckGroundingSpec", + "CheckGroundingRequest", + "CheckGroundingResponse", + }, +) + + +class GroundedGenerationContent(proto.Message): + r"""Base structured datatype containing multi-part content of a + message. + + Attributes: + role (str): + Producer of the content. Must be either ``user`` or + ``model``. + + Intended to be used for multi-turn conversations. Otherwise, + it can be left unset. + parts (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent.Part]): + Ordered ``Parts`` that constitute a single message. + """ + + class Part(proto.Message): + r"""Single part of content. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Inline text. + + This field is a member of `oneof`_ ``data``. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="data", + ) + + role: str = proto.Field( + proto.STRING, + number=1, + ) + parts: MutableSequence[Part] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Part, + ) + + +class GenerateGroundedContentRequest(proto.Message): + r"""Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + + Attributes: + location (str): + Required. Location resource. + + Format: ``projects/{project}/locations/{location}``. + system_instruction (google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent): + Content of the system instruction for the + current API. + These instructions will take priority over any + other prompt instructions if the selected model + is supporting them. + contents (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent]): + Content of the current conversation with the + model. + For single-turn queries, this is a single + instance. For multi-turn queries, this is a + repeated field that contains conversation + history + latest request. + generation_spec (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GenerationSpec): + Content generation specification. + grounding_spec (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSpec): + Grounding specification. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + class GenerationSpec(proto.Message): + r"""Content generation specification. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model_id (str): + Specifies which Vertex model id to use for + generation. + language_code (str): + Language code for content. Use language tags defined by + `BCP47 `__. + temperature (float): + If specified, custom value for the + temperature will be used. + + This field is a member of `oneof`_ ``_temperature``. + top_p (float): + If specified, custom value for nucleus + sampling will be used. + + This field is a member of `oneof`_ ``_top_p``. + top_k (int): + If specified, custom value for top-k sampling + will be used. + + This field is a member of `oneof`_ ``_top_k``. + frequency_penalty (float): + If specified, custom value for frequency + penalty will be used. + + This field is a member of `oneof`_ ``_frequency_penalty``. + presence_penalty (float): + If specified, custom value for presence + penalty will be used. + + This field is a member of `oneof`_ ``_presence_penalty``. + max_output_tokens (int): + If specified, custom value for max output + tokens will be used. + + This field is a member of `oneof`_ ``_max_output_tokens``. + """ + + model_id: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + temperature: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + top_p: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + top_k: int = proto.Field( + proto.INT32, + number=7, + optional=True, + ) + frequency_penalty: float = proto.Field( + proto.FLOAT, + number=8, + optional=True, + ) + presence_penalty: float = proto.Field( + proto.FLOAT, + number=9, + optional=True, + ) + max_output_tokens: int = proto.Field( + proto.INT32, + number=10, + optional=True, + ) + + class DynamicRetrievalConfiguration(proto.Message): + r"""Describes the options to customize dynamic retrieval. + + Attributes: + predictor (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor): + Specification for the predictor for dynamic + retrieval. + """ + + class DynamicRetrievalPredictor(proto.Message): + r"""Describes the predictor settings for dynamic retrieval. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + version (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor.Version): + The version of the predictor to be used in + dynamic retrieval. + threshold (float): + The value of the threshold. If the predictor + will predict a value smaller than this, it would + suppress grounding in the source. + + This field is a member of `oneof`_ ``_threshold``. + """ + + class Version(proto.Enum): + r"""The version of the predictor to be used in dynamic retrieval. + + Values: + VERSION_UNSPECIFIED (0): + Automatically choose the best version of the + retrieval predictor. + V1_INDEPENDENT (1): + The V1 model which is evaluating each source + independently. + """ + VERSION_UNSPECIFIED = 0 + V1_INDEPENDENT = 1 + + version: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor.Version" = proto.Field( + proto.ENUM, + number=1, + enum="GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor.Version", + ) + threshold: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + predictor: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor" = proto.Field( + proto.MESSAGE, + number=1, + message="GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor", + ) + + class GroundingSource(proto.Message): + r"""Grounding source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource.InlineSource): + If set, grounding is performed with inline + content. + + This field is a member of `oneof`_ ``source``. + search_source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource.SearchSource): + If set, grounding is performed with Vertex AI + Search. + + This field is a member of `oneof`_ ``source``. + google_search_source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource): + If set, grounding is performed with Google + Search. + + This field is a member of `oneof`_ ``source``. + """ + + class InlineSource(proto.Message): + r"""Message to be used for grounding based on inline content. + + Attributes: + grounding_facts (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundingFact]): + List of facts to be used for grounding. + attributes (MutableMapping[str, str]): + Attributes associated with the content. + + Common attributes include ``source`` (indicating where the + content was sourced from) and ``author`` (indicating the + author of the content). + """ + + grounding_facts: MutableSequence[ + grounding.GroundingFact + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=grounding.GroundingFact, + ) + attributes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + class SearchSource(proto.Message): + r"""Message to be used for grounding with Vertex AI Search. + + Attributes: + serving_config (str): + The resource name of the Engine to use. + + Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}/servingConfigs/{serving_config_id}`` + max_result_count (int): + Number of search results to return. + + The default value is 10. The maximumm allowed + value is 10. + filter (str): + Filter expression to be applied to the search. + + The syntax is the same as + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter]. + safe_search (bool): + If set, safe search is enabled in Vertex AI + Search requests. + """ + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + max_result_count: int = proto.Field( + proto.INT32, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class GoogleSearchSource(proto.Message): + r"""Google Search config parameters. + + Attributes: + dynamic_retrieval_config (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration): + Optional. Specifies the dynamic retrieval + configuration for the given source. + """ + + dynamic_retrieval_config: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration" = proto.Field( + proto.MESSAGE, + number=2, + message="GenerateGroundedContentRequest.DynamicRetrievalConfiguration", + ) + + inline_source: "GenerateGroundedContentRequest.GroundingSource.InlineSource" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message="GenerateGroundedContentRequest.GroundingSource.InlineSource", + ) + ) + search_source: "GenerateGroundedContentRequest.GroundingSource.SearchSource" = ( + proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message="GenerateGroundedContentRequest.GroundingSource.SearchSource", + ) + ) + google_search_source: "GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource", + ) + + class GroundingSpec(proto.Message): + r"""Grounding specification. + + Attributes: + grounding_sources (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource]): + Grounding sources. + """ + + grounding_sources: MutableSequence[ + "GenerateGroundedContentRequest.GroundingSource" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="GenerateGroundedContentRequest.GroundingSource", + ) + + location: str = proto.Field( + proto.STRING, + number=1, + ) + system_instruction: "GroundedGenerationContent" = proto.Field( + proto.MESSAGE, + number=5, + message="GroundedGenerationContent", + ) + contents: MutableSequence["GroundedGenerationContent"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="GroundedGenerationContent", + ) + generation_spec: GenerationSpec = proto.Field( + proto.MESSAGE, + number=3, + message=GenerationSpec, + ) + grounding_spec: GroundingSpec = proto.Field( + proto.MESSAGE, + number=4, + message=GroundingSpec, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + + +class GenerateGroundedContentResponse(proto.Message): + r"""Response for the ``GenerateGroundedContent`` method. + + Attributes: + candidates (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate]): + Generated candidates. + """ + + class Candidate(proto.Message): + r"""A response candidate generated from the model. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + index (int): + Index of the candidate. + content (google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent): + Content of the candidate. + grounding_score (float): + The overall grounding score for the candidate, in the range + of [0, 1]. + + This field is a member of `oneof`_ ``_grounding_score``. + grounding_metadata (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata): + Grounding metadata for the generated content. + """ + + class GroundingMetadata(proto.Message): + r"""Citation for the generated content. + + Attributes: + retrieval_metadata (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata]): + Retrieval metadata to provide an + understanding in the retrieval steps performed + by the model. There can be multiple such + messages which can correspond to different parts + of the retrieval. This is a mechanism used to + ensure transparency to our users. + support_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.FactChunk]): + List of chunks to be attributed across all + claims in the candidate. These are derived from + the grounding sources supplied in the request. + web_search_queries (MutableSequence[str]): + Web search queries for the following-up web + search. + search_entry_point (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.SearchEntryPoint): + Google search entry for the following-up web + searches. + grounding_support (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.GroundingSupport]): + GroundingSupport across all claims in the + answer candidate. An support to a fact indicates + that the claim is supported by the fact. + """ + + class RetrievalMetadata(proto.Message): + r"""Describes the metadata associated with a retrieval step. + + Attributes: + source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata.Source): + Describes the source to which the metadata is + referring to. + dynamic_retrieval_metadata (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalMetadata): + Metadata for dynamic retrieval. + """ + + class Source(proto.Enum): + r"""Describes the source to which the metadata is associated to. + + Values: + SOURCE_UNSPECIFIED (0): + Unspecified source. + VERTEX_AI_SEARCH (1): + Vertex AI search. + GOOGLE_SEARCH (3): + Google Search. + INLINE_CONTENT (2): + User inline provided content. + GOOGLE_MAPS (4): + Google Maps. + """ + SOURCE_UNSPECIFIED = 0 + VERTEX_AI_SEARCH = 1 + GOOGLE_SEARCH = 3 + INLINE_CONTENT = 2 + GOOGLE_MAPS = 4 + + source: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata.Source" = proto.Field( + proto.ENUM, + number=1, + enum="GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata.Source", + ) + dynamic_retrieval_metadata: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalMetadata", + ) + + class DynamicRetrievalMetadata(proto.Message): + r"""Describes the metadata about dynamic retrieval. + + Attributes: + predictor_metadata (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata): + Metadata for the dynamic retrieval predictor. + """ + + predictor_metadata: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata", + ) + + class DynamicRetrievalPredictorMetadata(proto.Message): + r"""Describes the metadata about the dynamic retrieval predictor. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + version (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata.Version): + The version of the predictor which was used + in dynamic retrieval. + prediction (float): + The value of the predictor. This should be between [0, 1] + where a value of 0 means that the query would not benefit + from grounding, while a value of 1.0 means that the query + would benefit the most. In between values allow to + differentiate between different usefulness scores for + grounding. + + This field is a member of `oneof`_ ``_prediction``. + """ + + class Version(proto.Enum): + r"""The version of the predictor which was used in dynamic + retrieval. + + Values: + VERSION_UNSPECIFIED (0): + Unspecified version, should never be used. + V1_INDEPENDENT (1): + The V1 model which is evaluating each source + independently. + """ + VERSION_UNSPECIFIED = 0 + V1_INDEPENDENT = 1 + + version: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata.Version" = proto.Field( + proto.ENUM, + number=1, + enum="GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata.Version", + ) + prediction: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + class SearchEntryPoint(proto.Message): + r"""Google search entry point. + + Attributes: + rendered_content (str): + Web content snippet that can be embedded in a + web page or an app webview. + sdk_blob (bytes): + Base64 encoded JSON representing array of + tuple. + """ + + rendered_content: str = proto.Field( + proto.STRING, + number=1, + ) + sdk_blob: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + class GroundingSupport(proto.Message): + r"""Grounding info for a claim in the candidate and its support. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + claim_text (str): + Text for the claim in the candidate. Always + provided when a support is found. + support_chunk_indices (MutableSequence[int]): + A list of indices (into 'support_chunks') specifying the + citations associated with the claim. For instance [1,3,4] + means that support_chunks[1], support_chunks[3], + support_chunks[4] are the chunks attributed to the claim. + support_score (float): + A score in the range of [0, 1] describing how grounded is a + specific claim in the support chunks indicated. Higher value + means that the claim is better supported by the chunks. + + This field is a member of `oneof`_ ``_support_score``. + """ + + claim_text: str = proto.Field( + proto.STRING, + number=1, + ) + support_chunk_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=3, + ) + support_score: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + retrieval_metadata: MutableSequence[ + "GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata", + ) + support_chunks: MutableSequence[grounding.FactChunk] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=grounding.FactChunk, + ) + web_search_queries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + search_entry_point: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.SearchEntryPoint" = proto.Field( + proto.MESSAGE, + number=4, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.SearchEntryPoint", + ) + grounding_support: MutableSequence[ + "GenerateGroundedContentResponse.Candidate.GroundingMetadata.GroundingSupport" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.GroundingSupport", + ) + + index: int = proto.Field( + proto.INT32, + number=1, + ) + content: "GroundedGenerationContent" = proto.Field( + proto.MESSAGE, + number=2, + message="GroundedGenerationContent", + ) + grounding_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + grounding_metadata: "GenerateGroundedContentResponse.Candidate.GroundingMetadata" = proto.Field( + proto.MESSAGE, + number=4, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata", + ) + + candidates: MutableSequence[Candidate] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Candidate, + ) + + +class CheckGroundingSpec(proto.Message): + r"""Specification for the grounding check. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + citation_threshold (float): + The threshold (in [0,1]) used for determining whether a fact + must be cited for a claim in the answer candidate. Choosing + a higher threshold will lead to fewer but very strong + citations, while choosing a lower threshold may lead to more + but somewhat weaker citations. If unset, the threshold will + default to 0.6. + + This field is a member of `oneof`_ ``_citation_threshold``. + """ + + citation_threshold: float = proto.Field( + proto.DOUBLE, + number=1, + optional=True, + ) + + +class CheckGroundingRequest(proto.Message): + r"""Request message for + [GroundedGenerationService.CheckGrounding][google.cloud.discoveryengine.v1beta.GroundedGenerationService.CheckGrounding] + method. + + Attributes: + grounding_config (str): + Required. The resource name of the grounding config, such as + ``projects/*/locations/global/groundingConfigs/default_grounding_config``. + answer_candidate (str): + Answer candidate to check. It can have a + maximum length of 4096 tokens. + facts (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundingFact]): + List of facts for the grounding check. + We support up to 200 facts. + grounding_spec (google.cloud.discoveryengine_v1beta.types.CheckGroundingSpec): + Configuration of the grounding check. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + grounding_config: str = proto.Field( + proto.STRING, + number=1, + ) + answer_candidate: str = proto.Field( + proto.STRING, + number=2, + ) + facts: MutableSequence[grounding.GroundingFact] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=grounding.GroundingFact, + ) + grounding_spec: "CheckGroundingSpec" = proto.Field( + proto.MESSAGE, + number=4, + message="CheckGroundingSpec", + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + + +class CheckGroundingResponse(proto.Message): + r"""Response message for the + [GroundedGenerationService.CheckGrounding][google.cloud.discoveryengine.v1beta.GroundedGenerationService.CheckGrounding] + method. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + support_score (float): + The support score for the input answer + candidate. Higher the score, higher is the + fraction of claims that are supported by the + provided facts. This is always set when a + response is returned. + + This field is a member of `oneof`_ ``_support_score``. + cited_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.FactChunk]): + List of facts cited across all claims in the + answer candidate. These are derived from the + facts supplied in the request. + cited_facts (MutableSequence[google.cloud.discoveryengine_v1beta.types.CheckGroundingResponse.CheckGroundingFactChunk]): + List of facts cited across all claims in the + answer candidate. These are derived from the + facts supplied in the request. + claims (MutableSequence[google.cloud.discoveryengine_v1beta.types.CheckGroundingResponse.Claim]): + Claim texts and citation info across all + claims in the answer candidate. + """ + + class CheckGroundingFactChunk(proto.Message): + r"""Fact chunk for grounding check. + + Attributes: + chunk_text (str): + Text content of the fact chunk. Can be at + most 10K characters long. + """ + + chunk_text: str = proto.Field( + proto.STRING, + number=1, + ) + + class Claim(proto.Message): + r"""Text and citation info for a claim in the answer candidate. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_pos (int): + Position indicating the start of the claim in + the answer candidate, measured in bytes. + + This field is a member of `oneof`_ ``_start_pos``. + end_pos (int): + Position indicating the end of the claim in + the answer candidate, exclusive. + + This field is a member of `oneof`_ ``_end_pos``. + claim_text (str): + Text for the claim in the answer candidate. + Always provided regardless of whether citations + or anti-citations are found. + citation_indices (MutableSequence[int]): + A list of indices (into 'cited_chunks') specifying the + citations associated with the claim. For instance [1,3,4] + means that cited_chunks[1], cited_chunks[3], cited_chunks[4] + are the facts cited supporting for the claim. A citation to + a fact indicates that the claim is supported by the fact. + grounding_check_required (bool): + Indicates that this claim required grounding check. When the + system decided this claim doesn't require + attribution/grounding check, this field will be set to + false. In that case, no grounding check was done for the + claim and therefore + [citation_indices][google.cloud.discoveryengine.v1beta.CheckGroundingResponse.Claim.citation_indices], + [anti_citation_indices][google.cloud.discoveryengine.v1beta.CheckGroundingResponse.Claim.anti_citation_indices], + and + [score][google.cloud.discoveryengine.v1beta.CheckGroundingResponse.Claim.score] + should not be returned. + + This field is a member of `oneof`_ ``_grounding_check_required``. + """ + + start_pos: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_pos: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + claim_text: str = proto.Field( + proto.STRING, + number=3, + ) + citation_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=4, + ) + grounding_check_required: bool = proto.Field( + proto.BOOL, + number=6, + optional=True, + ) + + support_score: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + cited_chunks: MutableSequence[grounding.FactChunk] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=grounding.FactChunk, + ) + cited_facts: MutableSequence[CheckGroundingFactChunk] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=CheckGroundingFactChunk, + ) + claims: MutableSequence[Claim] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Claim, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/grounding.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/grounding.py new file mode 100644 index 0000000000000000000000000000000000000000..c0a16c4c7d735d31153c65fe6754a4d76e03d8bf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/grounding.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GroundingConfig", + "GroundingFact", + "FactChunk", + }, +) + + +class GroundingConfig(proto.Message): + r"""Grounding configuration. + + Attributes: + name (str): + Required. Name of the GroundingConfig, of the form + ``projects/{project}/locations/{location}/groundingConfigs/{grounding_config}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroundingFact(proto.Message): + r"""Grounding Fact. + + Attributes: + fact_text (str): + Text content of the fact. Can be at most 10K + characters long. + attributes (MutableMapping[str, str]): + Attributes associated with the fact. Common attributes + include ``source`` (indicating where the fact was sourced + from), ``author`` (indicating the author of the fact), and + so on. + """ + + fact_text: str = proto.Field( + proto.STRING, + number=1, + ) + attributes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class FactChunk(proto.Message): + r"""Fact Chunk. + + Attributes: + chunk_text (str): + Text content of the fact chunk. Can be at + most 10K characters long. + source (str): + Source from which this fact chunk was + retrieved. If it was retrieved from the + GroundingFacts provided in the request then this + field will contain the index of the specific + fact from which this chunk was retrieved. + index (int): + The index of this chunk. Currently, only used + for the streaming mode. + source_metadata (MutableMapping[str, str]): + More fine-grained information for the source + reference. + """ + + chunk_text: str = proto.Field( + proto.STRING, + number=1, + ) + source: str = proto.Field( + proto.STRING, + number=2, + ) + index: int = proto.Field( + proto.INT32, + number=4, + ) + source_metadata: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/import_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/import_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c1458f15a46dc9533fde9974821dae00d8915408 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/import_config.py @@ -0,0 +1,1620 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + completion, + document, + sample_query, + user_event, +) + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GcsSource", + "BigQuerySource", + "SpannerSource", + "BigtableOptions", + "BigtableSource", + "FhirStoreSource", + "CloudSqlSource", + "AlloyDbSource", + "FirestoreSource", + "ImportErrorConfig", + "ImportUserEventsRequest", + "ImportUserEventsResponse", + "ImportUserEventsMetadata", + "ImportDocumentsMetadata", + "ImportDocumentsRequest", + "ImportDocumentsResponse", + "ImportSuggestionDenyListEntriesRequest", + "ImportSuggestionDenyListEntriesResponse", + "ImportSuggestionDenyListEntriesMetadata", + "ImportCompletionSuggestionsRequest", + "ImportCompletionSuggestionsResponse", + "ImportCompletionSuggestionsMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", + "ImportSampleQueriesMetadata", + }, +) + + +class GcsSource(proto.Message): + r"""Cloud Storage location for input content. + + Attributes: + input_uris (MutableSequence[str]): + Required. Cloud Storage URIs to input files. Each URI can be + up to 2000 characters long. URIs can match the full object + path (for example, ``gs://bucket/directory/object.json``) or + a pattern matching one or more files, such as + ``gs://bucket/directory/*.json``. + + A request can contain at most 100 files (or 100,000 files if + ``data_schema`` is ``content``). Each file can be up to 2 GB + (or 100 MB if ``data_schema`` is ``content``). + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for document imports: + + - ``document`` (default): One JSON + [Document][google.cloud.discoveryengine.v1beta.Document] + per line. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]. + - ``content``: Unstructured data (e.g. PDF, HTML). Each file + matched by ``input_uris`` becomes a document, with the ID + set to the first 128 bits of SHA256(URI) encoded as a hex + string. + - ``custom``: One custom data JSON per row in arbitrary + format that conforms to the defined + [Schema][google.cloud.discoveryengine.v1beta.Schema] of + the data store. This can only be used by the GENERIC Data + Store vertical. + - ``csv``: A CSV file with header conforming to the defined + [Schema][google.cloud.discoveryengine.v1beta.Schema] of + the data store. Each entry after the header is imported as + a Document. This can only be used by the GENERIC Data + Store vertical. + + Supported values for user event imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + per line. + """ + + input_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID or the project number that + contains the BigQuery source. Has a length limit + of 128 characters. If not specified, inherits + the project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for user event imports: + + - ``user_event`` (default): One + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + per row. + + Supported values for document imports: + + - ``document`` (default): One + [Document][google.cloud.discoveryengine.v1beta.Document] + format per row. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id] + and one of + [Document.json_data][google.cloud.discoveryengine.v1beta.Document.json_data] + or + [Document.struct_data][google.cloud.discoveryengine.v1beta.Document.struct_data]. + - ``custom``: One custom data per row in arbitrary format + that conforms to the defined + [Schema][google.cloud.discoveryengine.v1beta.Schema] of + the data store. This can only be used by the GENERIC Data + Store vertical. + """ + + partition_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=5, + oneof="partition", + message=date_pb2.Date, + ) + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + table_id: str = proto.Field( + proto.STRING, + number=3, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=4, + ) + data_schema: str = proto.Field( + proto.STRING, + number=6, + ) + + +class SpannerSource(proto.Message): + r"""The Spanner source for importing data + + Attributes: + project_id (str): + The project ID that contains the Spanner + source. Has a length limit of 128 characters. If + not specified, inherits the project ID from the + parent request. + instance_id (str): + Required. The instance ID of the source + Spanner table. + database_id (str): + Required. The database ID of the source + Spanner table. + table_id (str): + Required. The table name of the Spanner + database that needs to be imported. + enable_data_boost (bool): + Whether to apply data boost on Spanner export. Enabling this + option will incur additional cost. More info can be found + `here `__. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + database_id: str = proto.Field( + proto.STRING, + number=3, + ) + table_id: str = proto.Field( + proto.STRING, + number=4, + ) + enable_data_boost: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class BigtableOptions(proto.Message): + r"""The Bigtable Options object that contains information to + support the import. + + Attributes: + key_field_name (str): + The field name used for saving row key value in the + document. The name has to match the pattern + ``[a-zA-Z0-9][a-zA-Z0-9-_]*``. + families (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.BigtableOptions.BigtableColumnFamily]): + The mapping from family names to an object + that contains column families level information + for the given column family. If a family is not + present in this map it will be ignored. + """ + + class Type(proto.Enum): + r"""The type of values in a Bigtable column or column family. The values + are expected to be encoded using `HBase + Bytes.toBytes `__ + function when the encoding value is set to ``BINARY``. + + Values: + TYPE_UNSPECIFIED (0): + The type is unspecified. + STRING (1): + String type. + NUMBER (2): + Numerical type. + INTEGER (3): + Integer type. + VAR_INTEGER (4): + Variable length integer type. + BIG_NUMERIC (5): + BigDecimal type. + BOOLEAN (6): + Boolean type. + JSON (7): + JSON type. + """ + TYPE_UNSPECIFIED = 0 + STRING = 1 + NUMBER = 2 + INTEGER = 3 + VAR_INTEGER = 4 + BIG_NUMERIC = 5 + BOOLEAN = 6 + JSON = 7 + + class Encoding(proto.Enum): + r"""The encoding mode of a Bigtable column or column family. + + Values: + ENCODING_UNSPECIFIED (0): + The encoding is unspecified. + TEXT (1): + Text encoding. + BINARY (2): + Binary encoding. + """ + ENCODING_UNSPECIFIED = 0 + TEXT = 1 + BINARY = 2 + + class BigtableColumnFamily(proto.Message): + r"""The column family of the Bigtable. + + Attributes: + field_name (str): + The field name to use for this column family in the + document. The name has to match the pattern + ``[a-zA-Z0-9][a-zA-Z0-9-_]*``. If not set, it is parsed from + the family name with best effort. However, due to different + naming patterns, field name collisions could happen, where + parsing behavior is undefined. + encoding (google.cloud.discoveryengine_v1beta.types.BigtableOptions.Encoding): + The encoding mode of the values when the type is not STRING. + Acceptable encoding values are: + + - ``TEXT``: indicates values are alphanumeric text strings. + - ``BINARY``: indicates values are encoded using + ``HBase Bytes.toBytes`` family of functions. This can be + overridden for a specific column by listing that column in + ``columns`` and specifying an encoding for it. + type_ (google.cloud.discoveryengine_v1beta.types.BigtableOptions.Type): + The type of values in this column family. The values are + expected to be encoded using ``HBase Bytes.toBytes`` + function when the encoding value is set to ``BINARY``. + columns (MutableSequence[google.cloud.discoveryengine_v1beta.types.BigtableOptions.BigtableColumn]): + The list of objects that contains column + level information for each column. If a column + is not present in this list it will be ignored. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + encoding: "BigtableOptions.Encoding" = proto.Field( + proto.ENUM, + number=2, + enum="BigtableOptions.Encoding", + ) + type_: "BigtableOptions.Type" = proto.Field( + proto.ENUM, + number=3, + enum="BigtableOptions.Type", + ) + columns: MutableSequence[ + "BigtableOptions.BigtableColumn" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="BigtableOptions.BigtableColumn", + ) + + class BigtableColumn(proto.Message): + r"""The column of the Bigtable. + + Attributes: + qualifier (bytes): + Required. Qualifier of the column. If it + cannot be decoded with utf-8, use a base-64 + encoded string instead. + field_name (str): + The field name to use for this column in the document. The + name has to match the pattern ``[a-zA-Z0-9][a-zA-Z0-9-_]*``. + If not set, it is parsed from the qualifier bytes with best + effort. However, due to different naming patterns, field + name collisions could happen, where parsing behavior is + undefined. + encoding (google.cloud.discoveryengine_v1beta.types.BigtableOptions.Encoding): + The encoding mode of the values when the type is not + ``STRING``. Acceptable encoding values are: + + - ``TEXT``: indicates values are alphanumeric text strings. + - ``BINARY``: indicates values are encoded using + ``HBase Bytes.toBytes`` family of functions. This can be + overridden for a specific column by listing that column in + ``columns`` and specifying an encoding for it. + type_ (google.cloud.discoveryengine_v1beta.types.BigtableOptions.Type): + The type of values in this column family. The values are + expected to be encoded using ``HBase Bytes.toBytes`` + function when the encoding value is set to ``BINARY``. + """ + + qualifier: bytes = proto.Field( + proto.BYTES, + number=1, + ) + field_name: str = proto.Field( + proto.STRING, + number=2, + ) + encoding: "BigtableOptions.Encoding" = proto.Field( + proto.ENUM, + number=3, + enum="BigtableOptions.Encoding", + ) + type_: "BigtableOptions.Type" = proto.Field( + proto.ENUM, + number=4, + enum="BigtableOptions.Type", + ) + + key_field_name: str = proto.Field( + proto.STRING, + number=1, + ) + families: MutableMapping[str, BigtableColumnFamily] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=BigtableColumnFamily, + ) + + +class BigtableSource(proto.Message): + r"""The Cloud Bigtable source for importing data. + + Attributes: + project_id (str): + The project ID that contains the Bigtable + source. Has a length limit of 128 characters. If + not specified, inherits the project ID from the + parent request. + instance_id (str): + Required. The instance ID of the Cloud + Bigtable that needs to be imported. + table_id (str): + Required. The table ID of the Cloud Bigtable + that needs to be imported. + bigtable_options (google.cloud.discoveryengine_v1beta.types.BigtableOptions): + Required. Bigtable options that contains + information needed when parsing data into typed + structures. For example, column type + annotations. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + table_id: str = proto.Field( + proto.STRING, + number=3, + ) + bigtable_options: "BigtableOptions" = proto.Field( + proto.MESSAGE, + number=4, + message="BigtableOptions", + ) + + +class FhirStoreSource(proto.Message): + r"""Cloud FhirStore source import data from. + + Attributes: + fhir_store (str): + Required. The full resource name of the FHIR store to import + data from, in the format of + ``projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}``. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the FhirStore export to a specific Cloud + Storage directory. + resource_types (MutableSequence[str]): + The FHIR resource types to import. The resource types should + be a subset of all `supported FHIR resource + types `__. + Default to all supported FHIR resource types if empty. + """ + + fhir_store: str = proto.Field( + proto.STRING, + number=1, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=2, + ) + resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CloudSqlSource(proto.Message): + r"""Cloud SQL source import data from. + + Attributes: + project_id (str): + The project ID that contains the Cloud SQL + source. Has a length limit of 128 characters. If + not specified, inherits the project ID from the + parent request. + instance_id (str): + Required. The Cloud SQL instance to copy the + data from with a length limit of 256 characters. + database_id (str): + Required. The Cloud SQL database to copy the + data from with a length limit of 256 characters. + table_id (str): + Required. The Cloud SQL table to copy the + data from with a length limit of 256 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the Cloud SQL export to a specific Cloud + Storage directory. + + Ensure that the Cloud SQL service account has + the necessary Cloud Storage Admin permissions to + access the specified Cloud Storage directory. + offload (bool): + Option for serverless export. Enabling this option will + incur additional cost. More info can be found + `here `__. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + database_id: str = proto.Field( + proto.STRING, + number=3, + ) + table_id: str = proto.Field( + proto.STRING, + number=4, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=5, + ) + offload: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class AlloyDbSource(proto.Message): + r"""AlloyDB source import data from. + + Attributes: + project_id (str): + The project ID that contains the AlloyDB + source. Has a length limit of 128 characters. If + not specified, inherits the project ID from the + parent request. + location_id (str): + Required. The AlloyDB location to copy the + data from with a length limit of 256 characters. + cluster_id (str): + Required. The AlloyDB cluster to copy the + data from with a length limit of 256 characters. + database_id (str): + Required. The AlloyDB database to copy the + data from with a length limit of 256 characters. + table_id (str): + Required. The AlloyDB table to copy the data + from with a length limit of 256 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the AlloyDB export to a specific Cloud + Storage directory. + + Ensure that the AlloyDB service account has the + necessary Cloud Storage Admin permissions to + access the specified Cloud Storage directory. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + location_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_id: str = proto.Field( + proto.STRING, + number=4, + ) + table_id: str = proto.Field( + proto.STRING, + number=5, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=6, + ) + + +class FirestoreSource(proto.Message): + r"""Firestore source import data from. + + Attributes: + project_id (str): + The project ID that the Cloud SQL source is + in with a length limit of 128 characters. If not + specified, inherits the project ID from the + parent request. + database_id (str): + Required. The Firestore database to copy the + data from with a length limit of 256 characters. + collection_id (str): + Required. The Firestore collection (or + entity) to copy the data from with a length + limit of 1,500 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the Firestore export to a specific Cloud + Storage directory. + + Ensure that the Firestore service account has + the necessary Cloud Storage Admin permissions to + access the specified Cloud Storage directory. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + database_id: str = proto.Field( + proto.STRING, + number=2, + ) + collection_id: str = proto.Field( + proto.STRING, + number=3, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ImportErrorConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Cloud Storage prefix for import errors. This must be an + empty, existing Cloud Storage directory. Import errors are + written to sharded files in this directory, one per line, as + a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix: str = proto.Field( + proto.STRING, + number=1, + oneof="destination", + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest.InlineSource): + The Inline source for the input content for + UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. Parent DataStore resource name, of the form + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (MutableSequence[google.cloud.discoveryengine_v1beta.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=InlineSource, + ) + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GcsSource", + ) + bigquery_source: "BigQuerySource" = proto.Field( + proto.MESSAGE, + number=4, + oneof="source", + message="BigQuerySource", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="ImportErrorConfig", + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + Echoes the destination for the complete + errors if this field was set in the request. + joined_events_count (int): + Count of user events imported with complete + existing Documents. + unjoined_events_count (int): + Count of user events imported, but with + Document information not found in the existing + Branch. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="ImportErrorConfig", + ) + joined_events_count: int = proto.Field( + proto.INT64, + number=3, + ) + unjoined_events_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This is returned by the google.longrunning.Operation.metadata + field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the ImportDocuments + operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + total_count (int): + Total count of entries that were processed. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + total_count: int = proto.Field( + proto.INT64, + number=5, + ) + + +class ImportDocumentsRequest(proto.Message): + r"""Request message for Import methods. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest.InlineSource): + The Inline source for the input content for + documents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + fhir_store_source (google.cloud.discoveryengine_v1beta.types.FhirStoreSource): + FhirStore input source. + + This field is a member of `oneof`_ ``source``. + spanner_source (google.cloud.discoveryengine_v1beta.types.SpannerSource): + Spanner input source. + + This field is a member of `oneof`_ ``source``. + cloud_sql_source (google.cloud.discoveryengine_v1beta.types.CloudSqlSource): + Cloud SQL input source. + + This field is a member of `oneof`_ ``source``. + firestore_source (google.cloud.discoveryengine_v1beta.types.FirestoreSource): + Firestore input source. + + This field is a member of `oneof`_ ``source``. + alloy_db_source (google.cloud.discoveryengine_v1beta.types.AlloyDbSource): + AlloyDB input source. + + This field is a member of `oneof`_ ``source``. + bigtable_source (google.cloud.discoveryengine_v1beta.types.BigtableSource): + Cloud Bigtable input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Requires create/update permission. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + reconciliation_mode (google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest.ReconciliationMode): + The mode of reconciliation between existing documents and + the documents to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported documents to update. If not set, the + default is to update all fields. + auto_generate_ids (bool): + Whether to automatically generate IDs for the documents if + absent. + + If set to ``true``, + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s + are automatically generated based on the hash of the + payload, where IDs may not be consistent during multiple + imports. In which case + [ReconciliationMode.FULL][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.ReconciliationMode.FULL] + is highly recommended to avoid duplicate contents. If unset + or set to ``false``, + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s + have to be specified using + [id_field][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.id_field], + otherwise, documents without IDs fail to be imported. + + Supported data sources: + + - [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource]. + [GcsSource.data_schema][google.cloud.discoveryengine.v1beta.GcsSource.data_schema] + must be ``custom`` or ``csv``. Otherwise, an + INVALID_ARGUMENT error is thrown. + - [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource]. + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1beta.BigQuerySource.data_schema] + must be ``custom`` or ``csv``. Otherwise, an + INVALID_ARGUMENT error is thrown. + - [SpannerSource][google.cloud.discoveryengine.v1beta.SpannerSource]. + - [CloudSqlSource][google.cloud.discoveryengine.v1beta.CloudSqlSource]. + - [FirestoreSource][google.cloud.discoveryengine.v1beta.FirestoreSource]. + - [BigtableSource][google.cloud.discoveryengine.v1beta.BigtableSource]. + id_field (str): + The field indicates the ID field or column to be used as + unique IDs of the documents. + + For + [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] + it is the key of the JSON field. For instance, ``my_id`` for + JSON ``{"my_id": "some_uuid"}``. For others, it may be the + column name of the table where the unique ids are stored. + + The values of the JSON field or the table column are used as + the + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s. + The JSON field or the table column must be of string type, + and the values must be set as valid strings conform to + `RFC-1034 `__ with 1-63 + characters. Otherwise, documents without valid IDs fail to + be imported. + + Only set this field when + [auto_generate_ids][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.auto_generate_ids] + is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT + error is thrown. + + If it is unset, a default value ``_id`` is used when + importing from the allowed data sources. + + Supported data sources: + + - [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource]. + [GcsSource.data_schema][google.cloud.discoveryengine.v1beta.GcsSource.data_schema] + must be ``custom`` or ``csv``. Otherwise, an + INVALID_ARGUMENT error is thrown. + - [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource]. + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1beta.BigQuerySource.data_schema] + must be ``custom`` or ``csv``. Otherwise, an + INVALID_ARGUMENT error is thrown. + - [SpannerSource][google.cloud.discoveryengine.v1beta.SpannerSource]. + - [CloudSqlSource][google.cloud.discoveryengine.v1beta.CloudSqlSource]. + - [FirestoreSource][google.cloud.discoveryengine.v1beta.FirestoreSource]. + - [BigtableSource][google.cloud.discoveryengine.v1beta.BigtableSource]. + """ + + class ReconciliationMode(proto.Enum): + r"""Indicates how imported documents are reconciled with the + existing documents created or imported before. + + Values: + RECONCILIATION_MODE_UNSPECIFIED (0): + Defaults to ``INCREMENTAL``. + INCREMENTAL (1): + Inserts new documents or updates existing + documents. + FULL (2): + Calculates diff and replaces the entire + document dataset. Existing documents may be + deleted if they are not present in the source + location. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportDocuments + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Document]): + Required. A list of documents to update/create. Each + document must have a valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]. + Recommended max of 100 items. + """ + + documents: MutableSequence[document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=document.Document, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=InlineSource, + ) + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GcsSource", + ) + bigquery_source: "BigQuerySource" = proto.Field( + proto.MESSAGE, + number=4, + oneof="source", + message="BigQuerySource", + ) + fhir_store_source: "FhirStoreSource" = proto.Field( + proto.MESSAGE, + number=10, + oneof="source", + message="FhirStoreSource", + ) + spanner_source: "SpannerSource" = proto.Field( + proto.MESSAGE, + number=11, + oneof="source", + message="SpannerSource", + ) + cloud_sql_source: "CloudSqlSource" = proto.Field( + proto.MESSAGE, + number=12, + oneof="source", + message="CloudSqlSource", + ) + firestore_source: "FirestoreSource" = proto.Field( + proto.MESSAGE, + number=13, + oneof="source", + message="FirestoreSource", + ) + alloy_db_source: "AlloyDbSource" = proto.Field( + proto.MESSAGE, + number=14, + oneof="source", + message="AlloyDbSource", + ) + bigtable_source: "BigtableSource" = proto.Field( + proto.MESSAGE, + number=15, + oneof="source", + message="BigtableSource", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="ImportErrorConfig", + ) + reconciliation_mode: ReconciliationMode = proto.Field( + proto.ENUM, + number=6, + enum=ReconciliationMode, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + auto_generate_ids: bool = proto.Field( + proto.BOOL, + number=8, + ) + id_field: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ImportDocumentsResponse(proto.Message): + r"""Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="ImportErrorConfig", + ) + + +class ImportSuggestionDenyListEntriesRequest(proto.Message): + r"""Request message for + [CompletionService.ImportSuggestionDenyListEntries][google.cloud.discoveryengine.v1beta.CompletionService.ImportSuggestionDenyListEntries] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportSuggestionDenyListEntriesRequest.InlineSource): + The Inline source for the input content for + suggestion deny list entries. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + Only 1 file can be specified that contains all entries to + import. Supported values ``gcs_source.schema`` for + autocomplete suggestion deny list entry imports: + + - ``suggestion_deny_list`` (default): One JSON + [SuggestionDenyListEntry] per line. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent data store resource name for which to + import denylist entries. Follows pattern + projects/*/locations/*/collections/*/dataStores/*. + """ + + class InlineSource(proto.Message): + r"""The inline source for SuggestionDenyListEntry. + + Attributes: + entries (MutableSequence[google.cloud.discoveryengine_v1beta.types.SuggestionDenyListEntry]): + Required. A list of all denylist entries to + import. Max of 1000 items. + """ + + entries: MutableSequence[ + completion.SuggestionDenyListEntry + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=completion.SuggestionDenyListEntry, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=InlineSource, + ) + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GcsSource", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ImportSuggestionDenyListEntriesResponse(proto.Message): + r"""Response message for + [CompletionService.ImportSuggestionDenyListEntries][google.cloud.discoveryengine.v1beta.CompletionService.ImportSuggestionDenyListEntries] + method. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + imported_entries_count (int): + Count of deny list entries successfully + imported. + failed_entries_count (int): + Count of deny list entries that failed to be + imported. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + imported_entries_count: int = proto.Field( + proto.INT64, + number=2, + ) + failed_entries_count: int = proto.Field( + proto.INT64, + number=3, + ) + + +class ImportSuggestionDenyListEntriesMetadata(proto.Message): + r"""Metadata related to the progress of the + ImportSuggestionDenyListEntries operation. This is returned by + the google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ImportCompletionSuggestionsRequest(proto.Message): + r"""Request message for + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1beta.CompletionService.ImportCompletionSuggestions] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportCompletionSuggestionsRequest.InlineSource): + The Inline source for suggestion entries. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent data store resource name for which to + import customer autocomplete suggestions. + + Follows pattern + ``projects/*/locations/*/collections/*/dataStores/*`` + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + class InlineSource(proto.Message): + r"""The inline source for CompletionSuggestions. + + Attributes: + suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.CompletionSuggestion]): + Required. A list of all denylist entries to + import. Max of 1000 items. + """ + + suggestions: MutableSequence[ + completion.CompletionSuggestion + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=completion.CompletionSuggestion, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=InlineSource, + ) + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GcsSource", + ) + bigquery_source: "BigQuerySource" = proto.Field( + proto.MESSAGE, + number=4, + oneof="source", + message="BigQuerySource", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="ImportErrorConfig", + ) + + +class ImportCompletionSuggestionsResponse(proto.Message): + r"""Response of the + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1beta.CompletionService.ImportCompletionSuggestions] + method. If the long running operation is done, this message is + returned by the google.longrunning.Operations.response field if the + operation is successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="ImportErrorConfig", + ) + + +class ImportCompletionSuggestionsMetadata(proto.Message): + r"""Metadata related to the progress of the + ImportCompletionSuggestions operation. This will be returned by + the google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of + [CompletionSuggestion][google.cloud.discoveryengine.v1beta.CompletionSuggestion]s + successfully imported. + failure_count (int): + Count of + [CompletionSuggestion][google.cloud.discoveryengine.v1beta.CompletionSuggestion]s + that failed to be imported. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportSampleQueriesRequest(proto.Message): + r"""Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest.InlineSource): + The Inline source for sample query entries. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent sample query set resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + under this sample query set, regardless of whether or not + this sample query set exists, a ``PERMISSION_DENIED`` error + is returned. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + class InlineSource(proto.Message): + r"""The inline source for + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + + Attributes: + sample_queries (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuery]): + Required. A list of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to import. Max of 1000 items. + """ + + sample_queries: MutableSequence[sample_query.SampleQuery] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=sample_query.SampleQuery, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=InlineSource, + ) + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GcsSource", + ) + bigquery_source: "BigQuerySource" = proto.Field( + proto.MESSAGE, + number=4, + oneof="source", + message="BigQuerySource", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="ImportErrorConfig", + ) + + +class ImportSampleQueriesResponse(proto.Message): + r"""Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this message is + returned by the google.longrunning.Operations.response field if the + operation is successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="ImportErrorConfig", + ) + + +class ImportSampleQueriesMetadata(proto.Message): + r"""Metadata related to the progress of the ImportSampleQueries + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + ImportSampleQueries operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + ImportSampleQueries operation last update + time. If the operation is done, this is also the + finish time. + success_count (int): + Count of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + successfully imported. + failure_count (int): + Count of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + that failed to be imported. + total_count (int): + Total count of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + that were processed. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + total_count: int = proto.Field( + proto.INT64, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/project.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/project.py new file mode 100644 index 0000000000000000000000000000000000000000..63d811e112e31e9afe6ad155ba4325f531423549 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/project.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Project", + }, +) + + +class Project(proto.Message): + r"""Metadata and configurations for a Google Cloud project in the + service. + + Attributes: + name (str): + Output only. Full resource name of the project, for example + ``projects/{project}``. Note that when making requests, + project number and project id are both acceptable, but the + server will always respond in project number. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when this project + is created. + provision_completion_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when this project + is successfully provisioned. Empty value means + this project is still provisioning and is not + ready for use. + service_terms_map (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.Project.ServiceTerms]): + Output only. A map of terms of services. The key is the + ``id`` of + [ServiceTerms][google.cloud.discoveryengine.v1beta.Project.ServiceTerms]. + """ + + class ServiceTerms(proto.Message): + r"""Metadata about the terms of service. + + Attributes: + id (str): + The unique identifier of this terms of service. Available + terms: + + - ``GA_DATA_USE_TERMS``: `Terms for data + use `__. + When using this as ``id``, the acceptable + [version][google.cloud.discoveryengine.v1beta.Project.ServiceTerms.version] + to provide is ``2022-11-23``. + version (str): + The version string of the terms of service. For acceptable + values, see the comments for + [id][google.cloud.discoveryengine.v1beta.Project.ServiceTerms.id] + above. + state (google.cloud.discoveryengine_v1beta.types.Project.ServiceTerms.State): + Whether the project has accepted/rejected the + service terms or it is still pending. + accept_time (google.protobuf.timestamp_pb2.Timestamp): + The last time when the project agreed to the + terms of service. + decline_time (google.protobuf.timestamp_pb2.Timestamp): + The last time when the project declined or + revoked the agreement to terms of service. + """ + + class State(proto.Enum): + r"""The agreement states this terms of service. + + Values: + STATE_UNSPECIFIED (0): + The default value of the enum. This value is + not actually used. + TERMS_ACCEPTED (1): + The project has given consent to the terms of + service. + TERMS_PENDING (2): + The project is pending to review and accept + the terms of service. + TERMS_DECLINED (3): + The project has declined or revoked the + agreement to terms of service. + """ + STATE_UNSPECIFIED = 0 + TERMS_ACCEPTED = 1 + TERMS_PENDING = 2 + TERMS_DECLINED = 3 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + state: "Project.ServiceTerms.State" = proto.Field( + proto.ENUM, + number=4, + enum="Project.ServiceTerms.State", + ) + accept_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + decline_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + provision_completion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + service_terms_map: MutableMapping[str, ServiceTerms] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=ServiceTerms, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/project_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/project_service.py new file mode 100644 index 0000000000000000000000000000000000000000..45ddb4a7693e93b98684b3264638a57f48c63be1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/project_service.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "ProvisionProjectRequest", + "ProvisionProjectMetadata", + }, +) + + +class ProvisionProjectRequest(proto.Message): + r"""Request for + [ProjectService.ProvisionProject][google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject] + method. + + Attributes: + name (str): + Required. Full resource name of a + [Project][google.cloud.discoveryengine.v1beta.Project], such + as ``projects/{project_id_or_number}``. + accept_data_use_terms (bool): + Required. Set to ``true`` to specify that caller has read + and would like to give consent to the `Terms for data + use `__. + data_use_terms_version (str): + Required. The version of the `Terms for data + use `__ that + caller has read and would like to give consent to. + + Acceptable version is ``2022-11-23``, and this may change + over time. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + accept_data_use_terms: bool = proto.Field( + proto.BOOL, + number=2, + ) + data_use_terms_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ProvisionProjectMetadata(proto.Message): + r"""Metadata associated with a project provision operation.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/purge_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/purge_config.py new file mode 100644 index 0000000000000000000000000000000000000000..56a18e79d46941980bcffd2d3bd01d01ed688d78 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/purge_config.py @@ -0,0 +1,479 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import import_config + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "PurgeUserEventsRequest", + "PurgeUserEventsResponse", + "PurgeUserEventsMetadata", + "PurgeErrorConfig", + "PurgeDocumentsRequest", + "PurgeDocumentsResponse", + "PurgeDocumentsMetadata", + "PurgeSuggestionDenyListEntriesRequest", + "PurgeSuggestionDenyListEntriesResponse", + "PurgeSuggestionDenyListEntriesMetadata", + "PurgeCompletionSuggestionsRequest", + "PurgeCompletionSuggestionsResponse", + "PurgeCompletionSuggestionsMetadata", + }, +) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/{project}/locations/global/collections/{collection}/dataStores/{dataStore}``. + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. The + eligible fields for filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.discoveryengine.v1beta.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``userPseudoId``: Double quoted string. Specifying this + will delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType: ``eventType = "search"`` + - Deleting all events for a specific visitor: + ``userPseudoId = "visitor1024"`` + - Deleting all events inside a DataStore: ``*`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + The ``force`` field is currently not supported. Purge user + event requests will permanently delete all purgeable events. + Once the development is complete: If ``force`` is set to + false, the method will return the expected purge count + without deleting any user events. This field will default to + false if not included in the request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of events purged as a result + of the operation. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class PurgeUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeUserEvents + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class PurgeErrorConfig(proto.Message): + r"""Configuration of destination for Purge related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Cloud Storage prefix for purge errors. This must be an + empty, existing Cloud Storage directory. Purge errors are + written to sharded files in this directory, one per line, as + a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix: str = proto.Field( + proto.STRING, + number=1, + oneof="destination", + ) + + +class PurgeDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. Supported + ``data_schema``: + + - ``document_id``: One valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id] + per line. + + This field is a member of `oneof`_ ``source``. + inline_source (google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest.InlineSource): + Inline source for the input content for + purge. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + filter (str): + Required. Filter matching documents to purge. Only currently + supported value is ``*`` (all items). + error_config (google.cloud.discoveryengine_v1beta.types.PurgeErrorConfig): + The desired location of errors incurred + during the purge. + force (bool): + Actually performs the purge. If ``force`` is set to false, + return the expected purge count without deleting any + documents. + """ + + class InlineSource(proto.Message): + r"""The inline source for the input config for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. + + Attributes: + documents (MutableSequence[str]): + Required. A list of full resource name of documents to + purge. In the format + ``projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*``. + Recommended max of 100 items. + """ + + documents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + gcs_source: import_config.GcsSource = proto.Field( + proto.MESSAGE, + number=5, + oneof="source", + message=import_config.GcsSource, + ) + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=6, + oneof="source", + message=InlineSource, + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + error_config: "PurgeErrorConfig" = proto.Field( + proto.MESSAGE, + number=7, + message="PurgeErrorConfig", + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. If the long running operation is successfully done, then + this message is returned by the + google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of documents purged as a + result of the operation. + purge_sample (MutableSequence[str]): + A sample of document names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + purge_sample: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeDocuments + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + ignored_count (int): + Count of entries that were ignored as entries + were not found. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + ignored_count: int = proto.Field( + proto.INT64, + number=5, + ) + + +class PurgeSuggestionDenyListEntriesRequest(proto.Message): + r"""Request message for + [CompletionService.PurgeSuggestionDenyListEntries][google.cloud.discoveryengine.v1beta.CompletionService.PurgeSuggestionDenyListEntries] + method. + + Attributes: + parent (str): + Required. The parent data store resource name for which to + import denylist entries. Follows pattern + projects/*/locations/*/collections/*/dataStores/*. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PurgeSuggestionDenyListEntriesResponse(proto.Message): + r"""Response message for + [CompletionService.PurgeSuggestionDenyListEntries][google.cloud.discoveryengine.v1beta.CompletionService.PurgeSuggestionDenyListEntries] + method. + + Attributes: + purge_count (int): + Number of suggestion deny list entries + purged. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +class PurgeSuggestionDenyListEntriesMetadata(proto.Message): + r"""Metadata related to the progress of the + PurgeSuggestionDenyListEntries operation. This is returned by + the google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class PurgeCompletionSuggestionsRequest(proto.Message): + r"""Request message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1beta.CompletionService.PurgeCompletionSuggestions] + method. + + Attributes: + parent (str): + Required. The parent data store resource name for which to + purge completion suggestions. Follows pattern + projects/*/locations/*/collections/*/dataStores/*. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PurgeCompletionSuggestionsResponse(proto.Message): + r"""Response message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1beta.CompletionService.PurgeCompletionSuggestions] + method. + + Attributes: + purge_succeeded (bool): + Whether the completion suggestions were + successfully purged. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + purge_succeeded: bool = proto.Field( + proto.BOOL, + number=1, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +class PurgeCompletionSuggestionsMetadata(proto.Message): + r"""Metadata related to the progress of the + PurgeCompletionSuggestions operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/rank_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/rank_service.py new file mode 100644 index 0000000000000000000000000000000000000000..8ef6ba5911c09a35c75b8a27295d7604462e3c3f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/rank_service.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "RankingRecord", + "RankRequest", + "RankResponse", + }, +) + + +class RankingRecord(proto.Message): + r"""Record message for + [RankService.Rank][google.cloud.discoveryengine.v1beta.RankService.Rank] + method. + + Attributes: + id (str): + The unique ID to represent the record. + title (str): + The title of the record. Empty by default. At least one of + [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] + or + [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] + should be set otherwise an INVALID_ARGUMENT error is thrown. + content (str): + The content of the record. Empty by default. At least one of + [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] + or + [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] + should be set otherwise an INVALID_ARGUMENT error is thrown. + score (float): + The score of this record based on the given + query and selected model. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + content: str = proto.Field( + proto.STRING, + number=3, + ) + score: float = proto.Field( + proto.FLOAT, + number=4, + ) + + +class RankRequest(proto.Message): + r"""Request message for + [RankService.Rank][google.cloud.discoveryengine.v1beta.RankService.Rank] + method. + + Attributes: + ranking_config (str): + Required. The resource name of the rank service config, such + as + ``projects/{project_num}/locations/{location}/rankingConfigs/default_ranking_config``. + model (str): + The identifier of the model to use. It is one of: + + - ``semantic-ranker-512@latest``: Semantic ranking model + with maxiumn input token size 512. + + It is set to ``semantic-ranker-512@latest`` by default if + unspecified. + top_n (int): + The number of results to return. If this is + unset or no bigger than zero, returns all + results. + query (str): + The query to use. + records (MutableSequence[google.cloud.discoveryengine_v1beta.types.RankingRecord]): + Required. A list of records to rank. At most + 200 records to rank. + ignore_record_details_in_response (bool): + If true, the response will contain only + record ID and score. By default, it is false, + the response will contain record details. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + ranking_config: str = proto.Field( + proto.STRING, + number=1, + ) + model: str = proto.Field( + proto.STRING, + number=2, + ) + top_n: int = proto.Field( + proto.INT32, + number=3, + ) + query: str = proto.Field( + proto.STRING, + number=4, + ) + records: MutableSequence["RankingRecord"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="RankingRecord", + ) + ignore_record_details_in_response: bool = proto.Field( + proto.BOOL, + number=6, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class RankResponse(proto.Message): + r"""Response message for + [RankService.Rank][google.cloud.discoveryengine.v1beta.RankService.Rank] + method. + + Attributes: + records (MutableSequence[google.cloud.discoveryengine_v1beta.types.RankingRecord]): + A list of records sorted by descending score. + """ + + records: MutableSequence["RankingRecord"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="RankingRecord", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/recommendation_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/recommendation_service.py new file mode 100644 index 0000000000000000000000000000000000000000..51d09981d87b83373d5a915a1e841da8dd1a70bc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/recommendation_service.py @@ -0,0 +1,285 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import user_event as gcd_user_event +from google.cloud.discoveryengine_v1beta.types import document as gcd_document + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "RecommendRequest", + "RecommendResponse", + }, +) + + +class RecommendRequest(proto.Message): + r"""Request message for Recommend method. + + Attributes: + serving_config (str): + Required. Full resource name of a + [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig]: + ``projects/*/locations/global/collections/*/engines/*/servingConfigs/*``, + or + ``projects/*/locations/global/collections/*/dataStores/*/servingConfigs/*`` + + One default serving config is created along with your + recommendation engine creation. The engine ID is used as the + ID of the default serving config. For example, for Engine + ``projects/*/locations/global/collections/*/engines/my-engine``, + you can use + ``projects/*/locations/global/collections/*/engines/my-engine/servingConfigs/my-engine`` + for your + [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend] + requests. + user_event (google.cloud.discoveryengine_v1beta.types.UserEvent): + Required. Context about the user, what they are looking at + and what action they took to trigger the Recommend request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + or + [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1beta.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + to a random unique ID and leave + [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1beta.UserInfo.user_id] + unset. + page_size (int): + Maximum number of results to return. Set this + property to the number of recommendation results + needed. If zero, the service chooses a + reasonable default. The maximum allowed value is + 100. Values above 100 are set to 100. + filter (str): + Filter for restricting recommendation results with a length + limit of 5,000 characters. Currently, only filter + expressions on the ``filter_tags`` attribute is supported. + + Examples: + + - ``(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`` + - ``(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`` + + If ``attributeFilteringSyntax`` is set to true under the + ``params`` field, then attribute-based expressions are + expected instead of the above described tag-based syntax. + Examples: + + - (launguage: ANY("en", "es")) AND NOT (categories: + ANY("Movie")) + - (available: true) AND (launguage: ANY("en", "es")) OR + (categories: ANY("Movie")) + + If your filter blocks all results, the API returns generic + (unfiltered) popular Documents. If you only want results + strictly matching the filters, set ``strictFiltering`` to + ``true`` in + [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params] + to receive empty results instead. + + Note that the API never returns + [Document][google.cloud.discoveryengine.v1beta.Document]s + with ``storageStatus`` as ``EXPIRED`` or ``DELETED`` + regardless of filter choices. + validate_only (bool): + Use validate only mode for this recommendation query. If set + to ``true``, a fake model is used that returns arbitrary + Document IDs. Note that the validate only mode should only + be used for testing the API, or if the model is not ready. + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the + recommendations. + + Allowed values: + + - ``returnDocument``: Boolean. If set to ``true``, the + associated Document object is returned in + [RecommendResponse.RecommendationResult.document][google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.document]. + - ``returnScore``: Boolean. If set to true, the + recommendation score corresponding to each returned + Document is set in + [RecommendResponse.RecommendationResult.metadata][google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.metadata]. + The given score indicates the probability of a Document + conversion given the user's context and history. + - ``strictFiltering``: Boolean. True by default. If set to + ``false``, the service returns generic (unfiltered) + popular Documents instead of empty if your filter blocks + all recommendation results. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of: + + - ``no-diversity`` + - ``low-diversity`` + - ``medium-diversity`` + - ``high-diversity`` + - ``auto-diversity`` This gives request-level control and + adjusts recommendation results based on Document + category. + + - ``attributeFilteringSyntax``: Boolean. False by default. + If set to true, the ``filter`` field is interpreted + according to the new, attribute-based syntax. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Requirements for + labels `__ + for more details. + """ + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_user_event.UserEvent, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=6, + message=struct_pb2.Value, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class RecommendResponse(proto.Message): + r"""Response message for Recommend method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1beta.types.RecommendResponse.RecommendationResult]): + A list of recommended Documents. The order + represents the ranking (from the most relevant + Document to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + logs resulting from this recommendation, which enables + accurate attribution of recommendation model performance. + missing_ids (MutableSequence[str]): + IDs of documents in the request that were + missing from the default Branch associated with + the requested ServingConfig. + validate_only (bool): + True if + [RecommendRequest.validate_only][google.cloud.discoveryengine.v1beta.RecommendRequest.validate_only] + was set. + """ + + class RecommendationResult(proto.Message): + r"""RecommendationResult represents a generic recommendation + result with associated metadata. + + Attributes: + id (str): + Resource ID of the recommended Document. + document (google.cloud.discoveryengine_v1beta.types.Document): + Set if ``returnDocument`` is set to true in + [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params]. + metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional Document metadata or annotations. + + Possible values: + + - ``score``: Recommendation score in double value. Is set if + ``returnScore`` is set to true in + [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params]. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + results: MutableSequence[RecommendationResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RecommendationResult, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=2, + ) + missing_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query.py new file mode 100644 index 0000000000000000000000000000000000000000..90d23995902d0ed3df93b80d0b640c94eec316fe --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SampleQuery", + }, +) + + +class SampleQuery(proto.Message): + r"""Sample Query captures metadata to be used for evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + query_entry (google.cloud.discoveryengine_v1beta.types.SampleQuery.QueryEntry): + The query entry. + + This field is a member of `oneof`_ ``content``. + name (str): + Identifier. The full resource name of the sample query, in + the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + was created at. + """ + + class QueryEntry(proto.Message): + r"""Query Entry captures metadata to be used for search + evaluation. + + Attributes: + query (str): + Required. The query. + targets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuery.QueryEntry.Target]): + List of targets for the query. + """ + + class Target(proto.Message): + r"""Defines the parameters of the query's expected outcome. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Expected uri of the target. + + This field must be a UTF-8 encoded string with a length + limit of 2048 characters. + + Example of valid uris: ``https://example.com/abc``, + ``gcs://example/example.pdf``. + page_numbers (MutableSequence[int]): + Expected page numbers of the target. + + Each page number must be non negative. + score (float): + Relevance score of the target. + + This field is a member of `oneof`_ ``_score``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + page_numbers: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + score: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + + query: str = proto.Field( + proto.STRING, + number=1, + ) + targets: MutableSequence["SampleQuery.QueryEntry.Target"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SampleQuery.QueryEntry.Target", + ) + + query_entry: QueryEntry = proto.Field( + proto.MESSAGE, + number=2, + oneof="content", + message=QueryEntry, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_service.py new file mode 100644 index 0000000000000000000000000000000000000000..44db4975b6cefa7a5128bcf4508ee0d90ea10d7f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_service.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "CreateSampleQueryRequest", + "UpdateSampleQueryRequest", + "DeleteSampleQueryRequest", + }, +) + + +class GetSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSampleQueriesRequest(proto.Message): + r"""Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + + Attributes: + parent (str): + Required. The parent sample query set resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + under this sample query set, regardless of whether or not + this sample query set exists, a ``PERMISSION_DENIED`` error + is returned. + page_size (int): + Maximum number of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to return. If unspecified, defaults to 100. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListSampleQueriesResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListSampleQueriesResponse.next_page_token], + received from a previous + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSampleQueriesResponse(proto.Message): + r"""Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + + Attributes: + sample_queries (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuery]): + The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + next_page_token (str): + A token that can be sent as + [ListSampleQueriesRequest.page_token][google.cloud.discoveryengine.v1beta.ListSampleQueriesRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + sample_queries: MutableSequence[gcd_sample_query.SampleQuery] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to create. + sample_query_id (str): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1beta.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQueryRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_sample_query.SampleQuery, + ) + sample_query_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery] + method. + + Attributes: + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to update does not exist a ``NOT_FOUND`` error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'simple query' to update. If not set, + will by default update all fields. + """ + + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to delete does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_set.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_set.py new file mode 100644 index 0000000000000000000000000000000000000000..83ae097221ad2e1c29d33bf4f2d0d17a70b720e8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_set.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SampleQuerySet", + }, +) + + +class SampleQuerySet(proto.Message): + r"""A SampleQuerySet is the parent resource of SampleQuery, and + contains the configurations shared by all SampleQuery under it. + + Attributes: + name (str): + Identifier. The full resource name of the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + in the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + display_name (str): + Required. The sample query set display name. + + This field must be a UTF-8 encoded string with a + length limit of 128 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + was created at. + description (str): + The description of the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py new file mode 100644 index 0000000000000000000000000000000000000000..1dab3c6377bdd9413b81e37af37629cc03150331 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "CreateSampleQuerySetRequest", + "UpdateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + }, +) + + +class GetSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSampleQuerySetsRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + + Attributes: + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + under this location, regardless of whether or not this + location exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + to return. If unspecified, defaults to 100. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListSampleQuerySetsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListSampleQuerySetsResponse.next_page_token], + received from a previous + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSampleQuerySetsResponse(proto.Message): + r"""Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + + Attributes: + sample_query_sets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuerySet]): + The + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s. + next_page_token (str): + A token that can be sent as + [ListSampleQuerySetsRequest.page_token][google.cloud.discoveryengine.v1beta.ListSampleQuerySetsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + sample_query_sets: MutableSequence[ + gcd_sample_query_set.SampleQuerySet + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_sample_query_set.SampleQuerySet, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + sample_query_set (google.cloud.discoveryengine_v1beta.types.SampleQuerySet): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to create. + sample_query_set_id (str): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1beta.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQuerySetRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sample_query_set: gcd_sample_query_set.SampleQuerySet = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_sample_query_set.SampleQuerySet, + ) + sample_query_set_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet] + method. + + Attributes: + sample_query_set (google.cloud.discoveryengine_v1beta.types.SampleQuerySet): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to update does not exist a ``NOT_FOUND`` error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + imported 'sample query set' to update. If not + set, will by default update all fields. + """ + + sample_query_set: gcd_sample_query_set.SampleQuerySet = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query_set.SampleQuerySet, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to delete does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/schema.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..26a07ce369a892ff8e21adf9f12df70ad4d7f85d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/schema.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Schema", + }, +) + + +class Schema(proto.Message): + r"""Defines the structure and layout of a type of document data. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + struct_schema (google.protobuf.struct_pb2.Struct): + The structured representation of the schema. + + This field is a member of `oneof`_ ``schema``. + json_schema (str): + The JSON representation of the schema. + + This field is a member of `oneof`_ ``schema``. + name (str): + Immutable. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + """ + + struct_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof="schema", + message=struct_pb2.Struct, + ) + json_schema: str = proto.Field( + proto.STRING, + number=3, + oneof="schema", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/schema_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/schema_service.py new file mode 100644 index 0000000000000000000000000000000000000000..42437b4bf244f2183ffa30d69725ad3661ad4ab7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/schema_service.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetSchemaRequest", + "ListSchemasRequest", + "ListSchemasResponse", + "CreateSchemaRequest", + "UpdateSchemaRequest", + "DeleteSchemaRequest", + "CreateSchemaMetadata", + "UpdateSchemaMetadata", + "DeleteSchemaMetadata", + }, +) + + +class GetSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSchemasRequest(proto.Message): + r"""Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + page_size (int): + The maximum number of + [Schema][google.cloud.discoveryengine.v1beta.Schema]s to + return. The service may return fewer than this value. + + If unspecified, at most 100 + [Schema][google.cloud.discoveryengine.v1beta.Schema]s are + returned. + + The maximum value is 1000; values above 1000 are set to + 1000. + page_token (str): + A page token, received from a previous + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + must match the call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSchemasResponse(proto.Message): + r"""Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + Attributes: + schemas (MutableSequence[google.cloud.discoveryengine_v1beta.types.Schema]): + The [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + next_page_token (str): + A token that can be sent as + [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + schema (google.cloud.discoveryengine_v1beta.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1beta.Schema] to + create. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1beta.Schema], which + becomes the final component of the + [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. + + This field should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_schema.Schema, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] + method. + + Attributes: + schema (google.cloud.discoveryengine_v1beta.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1beta.Schema] to + update. + allow_missing (bool): + If set to true, and the + [Schema][google.cloud.discoveryengine.v1beta.Schema] is not + found, a new + [Schema][google.cloud.discoveryengine.v1beta.Schema] is + created. In this situation, ``update_mask`` is ignored. + """ + + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSchemaMetadata(proto.Message): + r"""Metadata for Create Schema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateSchemaMetadata(proto.Message): + r"""Metadata for UpdateSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteSchemaMetadata(proto.Message): + r"""Metadata for DeleteSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/search_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/search_service.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bd370797666703004b397832b5595923e6e025 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/search_service.py @@ -0,0 +1,2871 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import chunk as gcd_chunk +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import document as gcd_document + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SearchRequest", + "SearchResponse", + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + Attributes: + serving_config (str): + Required. The resource name of the Search serving config, + such as + ``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config``, + or + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. + This field is used to identify the serving configuration + name, set of models used to make the search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. + + Use ``default_branch`` as the branch ID or leave this field + empty, to search documents under the default branch. + query (str): + Raw search query. + image_query (google.cloud.discoveryengine_v1beta.types.SearchRequest.ImageQuery): + Raw image query. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to + return. The maximum allowed value depends on the data type. + Values above the maximum value are coerced to the maximum + value. + + - Websites with basic indexing: Default ``10``, Maximum + ``25``. + - Websites with advanced indexing: Default ``25``, Maximum + ``50``. + - Other: Default ``50``, Maximum ``100``. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + page_token (str): + A page token received from a previous + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Document][google.cloud.discoveryengine.v1beta.Document]s + deemed by the API as relevant) in search results. This field + is only considered if + [page_token][google.cloud.discoveryengine.v1beta.SearchRequest.page_token] + is unset. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + one_box_page_size (int): + The maximum number of results to return for + OneBox. This applies to each OneBox type + individually. Default number is 10. + data_store_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.DataStoreSpec]): + Specs defining dataStores to filter on in a + search call and configurations for those + dataStores. This is only considered for engines + with multiple dataStores use case. For single + dataStore within an engine, they should use the + specs at the top level. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. Filter expression is + case-sensitive. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + + Filtering in Vertex AI Search is done by mapping the LHS + filter key to a key property defined in the Vertex AI Search + backend -- this mapping is defined by the customer in their + schema. For example a media customer might have a field + 'name' in their schema. In this case the filter would look + like this: filter --> name:'ANY("king kong")' + + For more information about filtering including syntax and + filter operators, see + `Filter `__ + canonical_filter (str): + The default filter that is applied when a user performs a + search without checking any filters on the search page. + + The filter applied to every search request when quality + improvement such as query expansion is needed. In the case a + query does not have a sufficient amount of results this + filter will be used to determine whether or not to enable + the query expansion flow. The original filter will still be + used for the query expanded search. This field is strongly + recommended to achieve high search quality. + + For more information about filter syntax, see + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter]. + order_by (str): + The order in which documents are returned. Documents can be + ordered by a field in an + [Document][google.cloud.discoveryengine.v1beta.Document] + object. Leave it unset if ordered by relevance. ``order_by`` + expression is case-sensitive. + + For more information on ordering the website search results, + see `Order web search + results `__. + For more information on ordering the healthcare search + results, see `Order healthcare search + results `__. + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): + Information about the end user. Highly recommended for + analytics. + [UserInfo.user_agent][google.cloud.discoveryengine.v1beta.UserInfo.user_agent] + is used to deduce ``device_type`` for analytics. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see `Standard + fields `__. + This field helps to better interpret the query. If a value + isn't specified, the query language code is automatically + detected, which may not be accurate. + region_code (str): + The Unicode country/region code (CLDR) of a location, such + as "US" and "419". For more information, see `Standard + fields `__. + If set, then results will be boosted based on the + region_code provided. + facet_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + boost_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain documents. For more + information on boosting, see + `Boosting `__ + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional search parameters. + + For public website search only, supported values are: + + - ``user_country_code``: string. Default empty. If set to + non-empty, results are restricted or boosted based on the + location provided. For example, + ``user_country_code: "au"`` + + For available codes see `Country + Codes `__ + + - ``search_type``: double. Default empty. Enables + non-webpage searching depending on the value. The only + valid non-default value is 1, which enables image + searching. For example, ``search_type: 1`` + query_expansion_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that + specifies the conditions under which query + expansion occurs. + spell_correction_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + takes effect. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + and + [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.CompleteQueryRequest.user_pseudo_id] + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + content_search_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec): + A specification for configuring the behavior + of content search. + embedding_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.EmbeddingSpec): + Uses the provided embedding to do additional semantic + document retrieval. The retrieval is based on the dot + product of + [SearchRequest.EmbeddingSpec.EmbeddingVector.vector][google.cloud.discoveryengine.v1beta.SearchRequest.EmbeddingSpec.EmbeddingVector.vector] + and the document embedding that is provided in + [SearchRequest.EmbeddingSpec.EmbeddingVector.field_path][google.cloud.discoveryengine.v1beta.SearchRequest.EmbeddingSpec.EmbeddingVector.field_path]. + + If + [SearchRequest.EmbeddingSpec.EmbeddingVector.field_path][google.cloud.discoveryengine.v1beta.SearchRequest.EmbeddingSpec.EmbeddingVector.field_path] + is not provided, it will use + [ServingConfig.EmbeddingConfig.field_path][google.cloud.discoveryengine.v1beta.ServingConfig.embedding_config]. + ranking_expression (str): + The ranking expression controls the customized ranking on + retrieval documents. This overrides + [ServingConfig.ranking_expression][google.cloud.discoveryengine.v1beta.ServingConfig.ranking_expression]. + The syntax and supported features depend on the + ``ranking_expression_backend`` value. If + ``ranking_expression_backend`` is not provided, it defaults + to ``RANK_BY_EMBEDDING``. + + If + [ranking_expression_backend][google.cloud.discoveryengine.v1beta.SearchRequest.ranking_expression_backend] + is not provided or set to ``RANK_BY_EMBEDDING``, it should + be a single function or multiple functions that are joined + by "+". + + - ranking_expression = function, { " + ", function }; + + Supported functions: + + - double \* relevance_score + - double \* dotProduct(embedding_field_path) + + Function variables: + + - ``relevance_score``: pre-defined keywords, used for + measure relevance between query and document. + - ``embedding_field_path``: the document embedding field + used with query embedding vector. + - ``dotProduct``: embedding function between + ``embedding_field_path`` and query embedding vector. + + Example ranking expression: + + :: + + If document has an embedding field doc_embedding, the ranking expression + could be `0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)`. + + If + [ranking_expression_backend][google.cloud.discoveryengine.v1beta.SearchRequest.ranking_expression_backend] + is set to ``RANK_BY_FORMULA``, the following expression + types (and combinations of those chained using + or + + - operators) are supported: + + - ``double`` + - ``signal`` + - ``log(signal)`` + - ``exp(signal)`` + - ``rr(signal, double > 0)`` -- reciprocal rank + transformation with second argument being a denominator + constant. + - ``is_nan(signal)`` -- returns 0 if signal is NaN, 1 + otherwise. + - ``fill_nan(signal1, signal2 | double)`` -- if signal1 is + NaN, returns signal2 \| double, else returns signal1. + + Here are a few examples of ranking formulas that use the + supported ranking expression types: + + - ``0.2 * semantic_similarity_score + 0.8 * log(keyword_similarity_score)`` + -- mostly rank by the logarithm of + ``keyword_similarity_score`` with slight + ``semantic_smilarity_score`` adjustment. + - ``0.2 * exp(fill_nan(semantic_similarity_score, 0)) + 0.3 * is_nan(keyword_similarity_score)`` + -- rank by the exponent of ``semantic_similarity_score`` + filling the value with 0 if it's NaN, also add constant + 0.3 adjustment to the final score if + ``semantic_similarity_score`` is NaN. + - ``0.2 * rr(semantic_similarity_score, 16) + 0.8 * rr(keyword_similarity_score, 16)`` + -- mostly rank by the reciprocal rank of + ``keyword_similarity_score`` with slight adjustment of + reciprocal rank of ``semantic_smilarity_score``. + + The following signals are supported: + + - ``semantic_similarity_score``: semantic similarity + adjustment that is calculated using the embeddings + generated by a proprietary Google model. This score + determines how semantically similar a search query is to a + document. + - ``keyword_similarity_score``: keyword match adjustment + uses the Best Match 25 (BM25) ranking function. This score + is calculated using a probabilistic model to estimate the + probability that a document is relevant to a given query. + - ``relevance_score``: semantic relevance adjustment that + uses a proprietary Google model to determine the meaning + and intent behind a user's query in context with the + content in the documents. + - ``pctr_rank``: predicted conversion rate adjustment as a + rank use predicted Click-through rate (pCTR) to gauge the + relevance and attractiveness of a search result from a + user's perspective. A higher pCTR suggests that the result + is more likely to satisfy the user's query and intent, + making it a valuable signal for ranking. + - ``freshness_rank``: freshness adjustment as a rank + - ``document_age``: The time in hours elapsed since the + document was last updated, a floating-point number (e.g., + 0.25 means 15 minutes). + - ``topicality_rank``: topicality adjustment as a rank. Uses + proprietary Google model to determine the keyword-based + overlap between the query and the document. + - ``base_rank``: the default rank of the result + ranking_expression_backend (google.cloud.discoveryengine_v1beta.types.SearchRequest.RankingExpressionBackend): + The backend to use for the ranking expression + evaluation. + safe_search (bool): + Whether to turn on safe search. This is only + supported for website search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum of + 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can be + empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + natural_language_query_understanding_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec): + If ``naturalLanguageQueryUnderstandingSpec`` is not + specified, no additional natural language query + understanding will be done. + search_as_you_type_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.SearchAsYouTypeSpec): + Search as you type configuration. Only supported for the + [IndustryVertical.MEDIA][google.cloud.discoveryengine.v1beta.IndustryVertical.MEDIA] + vertical. + session (str): + The session resource name. Optional. + + Session allows users to do multi-turn /search + API calls or coordination between /search API + calls and /answer API calls. + + Example #1 (multi-turn /search API calls): + + - Call /search API with the session ID generated + in the first call. Here, the previous search + query gets considered in query standing. I.e., + if the first query is "How did Alphabet do in + 2022?" and the current query is "How about + 2023?", the current query will be interpreted + as "How did Alphabet do in 2023?". + + Example #2 (coordination between /search API + calls and /answer API calls): + + - Call /answer API with the session ID generated + in the first call. Here, the answer generation + happens in the context of the search results + from the first search call. + + Multi-turn Search feature is currently at + private GA stage. Please use v1alpha or v1beta + version instead before we launch this feature to + public GA. Or ask for allowlisting through + Google Support team. + session_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.SessionSpec): + Session specification. + + Can be used only when ``session`` is set. + relevance_threshold (google.cloud.discoveryengine_v1beta.types.SearchRequest.RelevanceThreshold): + The relevance threshold of the search + results. + Default to Google defined threshold, leveraging + a balance of precision and recall to deliver + both highly accurate results and comprehensive + coverage of relevant information. + personalization_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + + Notice that if both + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec] + and + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + are set, + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + overrides + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec]. + """ + + class RelevanceThreshold(proto.Enum): + r"""The relevance threshold of the search results. The higher + relevance threshold is, the higher relevant results are shown + and the less number of results are returned. + + Values: + RELEVANCE_THRESHOLD_UNSPECIFIED (0): + Default value. In this case, server behavior + defaults to Google defined threshold. + LOWEST (1): + Lowest relevance threshold. + LOW (2): + Low relevance threshold. + MEDIUM (3): + Medium relevance threshold. + HIGH (4): + High relevance threshold. + """ + RELEVANCE_THRESHOLD_UNSPECIFIED = 0 + LOWEST = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + + class RankingExpressionBackend(proto.Enum): + r"""The backend to use for the ranking expression evaluation. + + Values: + RANKING_EXPRESSION_BACKEND_UNSPECIFIED (0): + Default option for unspecified/unknown + values. + RANK_BY_EMBEDDING (3): + Ranking by custom embedding model, the + default way to evaluate the ranking expression. + RANK_BY_FORMULA (4): + Ranking by custom formula. + """ + RANKING_EXPRESSION_BACKEND_UNSPECIFIED = 0 + RANK_BY_EMBEDDING = 3 + RANK_BY_FORMULA = 4 + + class ImageQuery(proto.Message): + r"""Specifies the image query input. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_bytes (str): + Base64 encoded image bytes. Supported image + formats: JPEG, PNG, and BMP. + + This field is a member of `oneof`_ ``image``. + """ + + image_bytes: str = proto.Field( + proto.STRING, + number=1, + oneof="image", + ) + + class DataStoreSpec(proto.Message): + r"""A struct to define data stores to filter on in a search call and + configurations for those data stores. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + Attributes: + data_store (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + filter (str): + Optional. Filter specification to filter documents in the + data store specified by data_store field. For more + information on filtering, see + `Filtering `__ + """ + + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.discoveryengine_v1beta.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum facet values that are returned for this facet. If + unspecified, defaults to 20. The maximum allowed value is + 300. Values above 300 are coerced to 300. For aggregation in + healthcare search, when the [FacetKey.key] is + "healthcare_aggregation_key", the limit will be overridden + to 10,000 internally, regardless of the value set here. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + excluded_filter_keys (MutableSequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 documents with the color + facet "Red" and 200 documents with the color facet "Blue". A + query containing the filter "color:ANY("Red")" and having + "color" as + [FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" documents in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue documents + available, "Blue" would not be shown as an available facet + value. + + If "color" is listed in "excludedFilterKeys", then the query + returns the facet values "Red" with count 100 and "Blue" + with count 200, because the "color" key is now excluded from + the filter. Because this field doesn't affect search + results, the search results are still correctly filtered to + return only "Red" documents. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined automatically. If dynamic facets are enabled, it + is ordered together. If set to false, the position of this + facet in the response is the same as in the request, and it + is ranked before the facets with dynamic position enable and + all dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response is determined automatically. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enabled, which generates + a facet ``gender``. Then the final order of the facets in + the response can be ("price", "brands", "rating", "gender") + or ("price", "brands", "gender", "rating") depends on how + API orders "gender" and "rating" facets. However, notice + that "price" and "brands" are always ranked at first and + second position because their enable_dynamic_position is + false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Document][google.cloud.discoveryengine.v1beta.Document] + object, over which the facet values are computed. Facet key + is case-sensitive. + intervals (MutableSequence[google.cloud.discoveryengine_v1beta.types.Interval]): + Set only if values should be bucketed into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (MutableSequence[str]): + Only get facet for the given restricted values. Only + supported on textual fields. For example, suppose "category" + has three values "Action > 2022", "Action > 2021" and + "Sci-Fi > 2022". If set "restricted_values" to "Action > + 2022", the "category" facet only contains "Action > 2022". + Only supported on textual fields. Maximum is 10. + prefixes (MutableSequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "category" has three values "Action > 2022", + "Action > 2021" and "Sci-Fi > 2022". If set + "prefixes" to "Action", the "category" facet + only contains "Action > 2022" and "Action > + 2021". Only supported on textual fields. Maximum + is 10. + contains (MutableSequence[str]): + Only get facet values that contain the given + strings. For example, suppose "category" has + three values "Action > 2022", "Action > 2021" + and "Sci-Fi > 2022". If set "contains" to + "2022", the "category" facet only contains + "Action > 2022" and "Sci-Fi > 2022". Only + supported on textual fields. Maximum is 10. + case_insensitive (bool): + True to make facet keys case insensitive when + getting faceting values with prefixes or + contains; false otherwise. + order_by (str): + The order in which documents are returned. + + Allowed values are: + + - "count desc", which means order by + [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1beta.SearchResponse.Facet.FacetValue.count] + descending. + + - "value desc", which means order by + [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1beta.SearchResponse.Facet.FacetValue.value] + descending. Only applies to textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.intervals]. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + intervals: MutableSequence[common.Interval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + contains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + case_insensitive: bool = proto.Field( + proto.BOOL, + number=6, + ) + order_by: str = proto.Field( + proto.STRING, + number=7, + ) + + facet_key: "SearchRequest.FacetSpec.FacetKey" = proto.Field( + proto.MESSAGE, + number=1, + message="SearchRequest.FacetSpec.FacetKey", + ) + limit: int = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position: bool = proto.Field( + proto.BOOL, + number=4, + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain documents. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a document + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to documents which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost documents with document ID "doc_1" or "doc_2", + and color "Red" or "Blue": + ``(document_id: ANY("doc_1", "doc_2")) AND (color: ANY("Red", "Blue"))`` + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the document a big promotion. However, + it does not necessarily mean that the boosted document will + be the top result at all times, nor that other documents + will be excluded. Results could still be shown even when + none of them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant documents. + + Setting to -1.0 gives the document a big demotion. However, + results that are deeply relevant might still be shown. The + document will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. Only one of the (condition, boost) + combination or the boost_control_spec below are set. If both + are set then the global boost is ignored and the more + fine-grained boost_control_spec is applied. + boost_control_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec): + Complex specification for custom ranking + based on customer defined attribute value. + """ + + class BoostControlSpec(proto.Message): + r"""Specification for custom ranking based on customer specified + attribute value. It provides more controls for customized + ranking than the simple (condition, boost) combination above. + + Attributes: + field_name (str): + The name of the field whose value will be + used to determine the boost amount. + attribute_type (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.AttributeType): + The attribute type to be used to determine the boost amount. + The attribute value can be derived from the field value of + the specified field_name. In the case of numerical it is + straightforward i.e. attribute_value = + numerical_field_value. In the case of freshness however, + attribute_value = (time.now() - datetime_field_value). + interpolation_type (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.InterpolationType): + The interpolation type to be applied to + connect the control points listed below. + control_points (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.ControlPoint]): + The control points used to define the curve. The monotonic + function (defined through the interpolation_type above) + passes through the control points listed here. + """ + + class AttributeType(proto.Enum): + r"""The attribute(or function) for which the custom ranking is to + be applied. + + Values: + ATTRIBUTE_TYPE_UNSPECIFIED (0): + Unspecified AttributeType. + NUMERICAL (1): + The value of the numerical field will be used to dynamically + update the boost amount. In this case, the attribute_value + (the x value) of the control point will be the actual value + of the numerical field for which the boost_amount is + specified. + FRESHNESS (2): + For the freshness use case the attribute value will be the + duration between the current time and the date in the + datetime field specified. The value must be formatted as an + XSD ``dayTimeDuration`` value (a restricted subset of an ISO + 8601 duration value). The pattern for this is: + ``[nD][T[nH][nM][nS]]``. For example, ``5D``, ``3DT12H30M``, + ``T24H``. + """ + ATTRIBUTE_TYPE_UNSPECIFIED = 0 + NUMERICAL = 1 + FRESHNESS = 2 + + class InterpolationType(proto.Enum): + r"""The interpolation type to be applied. Default will be linear + (Piecewise Linear). + + Values: + INTERPOLATION_TYPE_UNSPECIFIED (0): + Interpolation type is unspecified. In this + case, it defaults to Linear. + LINEAR (1): + Piecewise linear interpolation will be + applied. + """ + INTERPOLATION_TYPE_UNSPECIFIED = 0 + LINEAR = 1 + + class ControlPoint(proto.Message): + r"""The control points used to define the curve. The curve + defined through these control points can only be monotonically + increasing or decreasing(constant values are acceptable). + + Attributes: + attribute_value (str): + Can be one of: + + 1. The numerical field value. + 2. The duration spec for freshness: The value must be + formatted as an XSD ``dayTimeDuration`` value (a + restricted subset of an ISO 8601 duration value). The + pattern for this is: ``[nD][T[nH][nM][nS]]``. + boost_amount (float): + The value between -1 to 1 by which to boost the score if the + attribute_value evaluates to the value specified above. + """ + + attribute_value: str = proto.Field( + proto.STRING, + number=1, + ) + boost_amount: float = proto.Field( + proto.FLOAT, + number=2, + ) + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + attribute_type: "SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.AttributeType" = proto.Field( + proto.ENUM, + number=2, + enum="SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.AttributeType", + ) + interpolation_type: "SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.InterpolationType" = proto.Field( + proto.ENUM, + number=3, + enum="SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.InterpolationType", + ) + control_points: MutableSequence[ + "SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.ControlPoint" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec.ControlPoint", + ) + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + boost_control_spec: "SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec" = proto.Field( + proto.MESSAGE, + number=3, + message="SearchRequest.BoostSpec.ConditionBoostSpec.BoostControlSpec", + ) + + condition_boost_specs: MutableSequence[ + "SearchRequest.BoostSpec.ConditionBoostSpec" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchRequest.BoostSpec.ConditionBoostSpec", + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.discoveryengine_v1beta.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + + Values: + CONDITION_UNSPECIFIED (0): + Unspecified query expansion condition. In this case, server + behavior defaults to + [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + DISABLED (1): + Disabled query expansion. Only the exact search query is + used, even if + [SearchResponse.total_size][google.cloud.discoveryengine.v1beta.SearchResponse.total_size] + is zero. + AUTO (2): + Automatic query expansion built by the Search + API. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 2 + + condition: "SearchRequest.QueryExpansionSpec.Condition" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.QueryExpansionSpec.Condition", + ) + pin_unexpanded_results: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction replaces the original + search query. Defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + + Values: + MODE_UNSPECIFIED (0): + Unspecified spell correction mode. In this case, server + behavior defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + SUGGESTION_ONLY (1): + Search API tries to find a spelling suggestion. If a + suggestion is found, it is put in the + [SearchResponse.corrected_query][google.cloud.discoveryengine.v1beta.SearchResponse.corrected_query]. + The spelling suggestion won't be used as the search query. + AUTO (2): + Automatic spell correction built by the + Search API. Search will be based on the + corrected query if found. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode: "SearchRequest.SpellCorrectionSpec.Mode" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.SpellCorrectionSpec.Mode", + ) + + class ContentSearchSpec(proto.Message): + r"""A specification for configuring the behavior of content + search. + + Attributes: + snippet_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SnippetSpec): + If ``snippetSpec`` is not specified, snippets are not + included in the search response. + summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec): + If ``summarySpec`` is not specified, summaries are not + included in the search response. + extractive_content_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.ExtractiveContentSpec): + If there is no extractive_content_spec provided, there will + be no extractive answer in the search response. + search_result_mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SearchResultMode): + Specifies the search result mode. If unspecified, the search + result mode defaults to ``DOCUMENTS``. + chunk_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.ChunkSpec): + Specifies the chunk spec to be returned from the search + response. Only available if the + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS] + """ + + class SearchResultMode(proto.Enum): + r"""Specifies the search result mode. If unspecified, the search result + mode defaults to ``DOCUMENTS``. + + Values: + SEARCH_RESULT_MODE_UNSPECIFIED (0): + Default value. + DOCUMENTS (1): + Returns documents in the search result. + CHUNKS (2): + Returns chunks in the search result. Only available if the + [DataStore.DocumentProcessingConfig.chunking_config][] is + specified. + """ + SEARCH_RESULT_MODE_UNSPECIFIED = 0 + DOCUMENTS = 1 + CHUNKS = 2 + + class SnippetSpec(proto.Message): + r"""A specification for configuring snippets in a search + response. + + Attributes: + max_snippet_count (int): + [DEPRECATED] This field is deprecated. To control snippet + return, use ``return_snippet`` field. For backwards + compatibility, we will return snippet if max_snippet_count > + 0. + reference_only (bool): + [DEPRECATED] This field is deprecated and will have no + affect on the snippet. + return_snippet (bool): + If ``true``, then return snippet. If no snippet can be + generated, we return "No snippet is available for this + page." A ``snippet_status`` with ``SUCCESS`` or + ``NO_SNIPPET_AVAILABLE`` will also be returned. + """ + + max_snippet_count: int = proto.Field( + proto.INT32, + number=1, + ) + reference_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + return_snippet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SummarySpec(proto.Message): + r"""A specification for configuring a summary returned in a + search response. + + Attributes: + summary_result_count (int): + The number of top results to generate the summary from. If + the number of results returned is less than + ``summaryResultCount``, the summary is generated from all of + the results. + + At most 10 results for documents mode, or 50 for chunks + mode, can be used to generate a summary. The chunks mode is + used when + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS]. + include_citations (bool): + Specifies whether to include citations in the summary. The + default value is ``false``. + + When this field is set to ``true``, summaries include + in-line citation numbers. + + Example summary including citations: + + BigQuery is Google Cloud's fully managed and completely + serverless enterprise data warehouse [1]. BigQuery supports + all data types, works across clouds, and has built-in + machine learning and business intelligence, all within a + unified platform [2, 3]. + + The citation numbers refer to the returned search results + and are 1-indexed. For example, [1] means that the sentence + is attributed to the first search result. [2, 3] means that + the sentence is attributed to both the second and third + search results. + ignore_adversarial_query (bool): + Specifies whether to filter out adversarial queries. The + default value is ``false``. + + Google employs search-query classification to detect + adversarial queries. No summary is returned if the search + query is classified as an adversarial query. For example, a + user might ask a question regarding negative comments about + the company or submit a query designed to generate unsafe, + policy-violating output. If this field is set to ``true``, + we skip generating summaries for adversarial queries and + return fallback messages instead. + ignore_non_summary_seeking_query (bool): + Specifies whether to filter out queries that are not + summary-seeking. The default value is ``false``. + + Google employs search-query classification to detect + summary-seeking queries. No summary is returned if the + search query is classified as a non-summary seeking query. + For example, ``why is the sky blue`` and + ``Who is the best soccer player in the world?`` are + summary-seeking queries, but ``SFO airport`` and + ``world cup 2026`` are not. They are most likely + navigational queries. If this field is set to ``true``, we + skip generating summaries for non-summary seeking queries + and return fallback messages instead. + ignore_low_relevant_content (bool): + Specifies whether to filter out queries that have low + relevance. The default value is ``false``. + + If this field is set to ``false``, all search results are + used regardless of relevance to generate answers. If set to + ``true``, only queries with high relevance search results + will generate answers. + ignore_jail_breaking_query (bool): + Optional. Specifies whether to filter out jail-breaking + queries. The default value is ``false``. + + Google employs search-query classification to detect + jail-breaking queries. No summary is returned if the search + query is classified as a jail-breaking query. A user might + add instructions to the query to change the tone, style, + language, content of the answer, or ask the model to act as + a different entity, e.g. "Reply in the tone of a competing + company's CEO". If this field is set to ``true``, we skip + generating summaries for jail-breaking queries and return + fallback messages instead. + model_prompt_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec): + If specified, the spec will be used to modify + the prompt provided to the LLM. + language_code (str): + Language code for Summary. Use language tags defined by + `BCP47 `__. + Note: This is an experimental feature. + model_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec): + If specified, the spec will be used to modify + the model specification provided to the LLM. + use_semantic_chunks (bool): + If true, answer will be generated from most + relevant chunks from top search results. This + feature will improve summary quality. Note that + with this feature enabled, not all top search + results will be referenced and included in the + reference list, so the citation source index + only points to the search results listed in the + reference list. + """ + + class ModelPromptSpec(proto.Message): + r"""Specification of the prompt to use with the model. + + Attributes: + preamble (str): + Text at the beginning of the prompt that + instructs the assistant. Examples are available + in the user guide. + """ + + preamble: str = proto.Field( + proto.STRING, + number=1, + ) + + class ModelSpec(proto.Message): + r"""Specification of the model. + + Attributes: + version (str): + The model version used to generate the summary. + + Supported values are: + + - ``stable``: string. Default value when no value is + specified. Uses a generally available, fine-tuned model. + For more information, see `Answer generation model + versions and + lifecycle `__. + - ``preview``: string. (Public preview) Uses a preview + model. For more information, see `Answer generation model + versions and + lifecycle `__. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + + summary_result_count: int = proto.Field( + proto.INT32, + number=1, + ) + include_citations: bool = proto.Field( + proto.BOOL, + number=2, + ) + ignore_adversarial_query: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_non_summary_seeking_query: bool = proto.Field( + proto.BOOL, + number=4, + ) + ignore_low_relevant_content: bool = proto.Field( + proto.BOOL, + number=9, + ) + ignore_jail_breaking_query: bool = proto.Field( + proto.BOOL, + number=10, + ) + model_prompt_spec: "SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec" = proto.Field( + proto.MESSAGE, + number=5, + message="SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec", + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + model_spec: "SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec" = ( + proto.Field( + proto.MESSAGE, + number=7, + message="SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec", + ) + ) + use_semantic_chunks: bool = proto.Field( + proto.BOOL, + number=8, + ) + + class ExtractiveContentSpec(proto.Message): + r"""A specification for configuring the extractive content in a + search response. + + Attributes: + max_extractive_answer_count (int): + The maximum number of extractive answers returned in each + search result. + + An extractive answer is a verbatim answer extracted from the + original document, which provides a precise and contextually + relevant answer to the search query. + + If the number of matching answers is less than the + ``max_extractive_answer_count``, return all of the answers. + Otherwise, return the ``max_extractive_answer_count``. + + At most five answers are returned for each + [SearchResult][google.cloud.discoveryengine.v1beta.SearchResponse.SearchResult]. + max_extractive_segment_count (int): + The max number of extractive segments returned in each + search result. Only applied if the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + is set to + [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.CONTENT_REQUIRED] + or + [DataStore.solution_types][google.cloud.discoveryengine.v1beta.DataStore.solution_types] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_CHAT]. + + An extractive segment is a text segment extracted from the + original document that is relevant to the search query, and, + in general, more verbose than an extractive answer. The + segment could then be used as input for LLMs to generate + summaries and answers. + + If the number of matching segments is less than + ``max_extractive_segment_count``, return all of the + segments. Otherwise, return the + ``max_extractive_segment_count``. + return_extractive_segment_score (bool): + Specifies whether to return the confidence score from the + extractive segments in each search result. This feature is + available only for new or allowlisted data stores. To + allowlist your data store, contact your Customer Engineer. + The default value is ``false``. + num_previous_segments (int): + Specifies whether to also include the adjacent from each + selected segments. Return at most ``num_previous_segments`` + segments before each selected segments. + num_next_segments (int): + Return at most ``num_next_segments`` segments after each + selected segments. + """ + + max_extractive_answer_count: int = proto.Field( + proto.INT32, + number=1, + ) + max_extractive_segment_count: int = proto.Field( + proto.INT32, + number=2, + ) + return_extractive_segment_score: bool = proto.Field( + proto.BOOL, + number=3, + ) + num_previous_segments: int = proto.Field( + proto.INT32, + number=4, + ) + num_next_segments: int = proto.Field( + proto.INT32, + number=5, + ) + + class ChunkSpec(proto.Message): + r"""Specifies the chunk spec to be returned from the search response. + Only available if the + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS] + + Attributes: + num_previous_chunks (int): + The number of previous chunks to be returned + of the current chunk. The maximum allowed value + is 3. If not specified, no previous chunks will + be returned. + num_next_chunks (int): + The number of next chunks to be returned of + the current chunk. The maximum allowed value is + 3. If not specified, no next chunks will be + returned. + """ + + num_previous_chunks: int = proto.Field( + proto.INT32, + number=1, + ) + num_next_chunks: int = proto.Field( + proto.INT32, + number=2, + ) + + snippet_spec: "SearchRequest.ContentSearchSpec.SnippetSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="SearchRequest.ContentSearchSpec.SnippetSpec", + ) + summary_spec: "SearchRequest.ContentSearchSpec.SummarySpec" = proto.Field( + proto.MESSAGE, + number=2, + message="SearchRequest.ContentSearchSpec.SummarySpec", + ) + extractive_content_spec: "SearchRequest.ContentSearchSpec.ExtractiveContentSpec" = proto.Field( + proto.MESSAGE, + number=3, + message="SearchRequest.ContentSearchSpec.ExtractiveContentSpec", + ) + search_result_mode: "SearchRequest.ContentSearchSpec.SearchResultMode" = ( + proto.Field( + proto.ENUM, + number=4, + enum="SearchRequest.ContentSearchSpec.SearchResultMode", + ) + ) + chunk_spec: "SearchRequest.ContentSearchSpec.ChunkSpec" = proto.Field( + proto.MESSAGE, + number=5, + message="SearchRequest.ContentSearchSpec.ChunkSpec", + ) + + class EmbeddingSpec(proto.Message): + r"""The specification that uses customized query embedding vector + to do semantic document retrieval. + + Attributes: + embedding_vectors (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.EmbeddingSpec.EmbeddingVector]): + The embedding vector used for retrieval. + Limit to 1. + """ + + class EmbeddingVector(proto.Message): + r"""Embedding vector. + + Attributes: + field_path (str): + Embedding field path in schema. + vector (MutableSequence[float]): + Query embedding vector. + """ + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + vector: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + embedding_vectors: MutableSequence[ + "SearchRequest.EmbeddingSpec.EmbeddingVector" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchRequest.EmbeddingSpec.EmbeddingVector", + ) + + class NaturalLanguageQueryUnderstandingSpec(proto.Message): + r"""Specification to enable natural language understanding + capabilities for search requests. + + Attributes: + filter_extraction_condition (google.cloud.discoveryengine_v1beta.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition): + The condition under which filter extraction should occur. + Default to [Condition.DISABLED][]. + geo_search_query_detection_field_names (MutableSequence[str]): + Field names used for location-based filtering, where + geolocation filters are detected in natural language search + queries. Only valid when the FilterExtractionCondition is + set to ``ENABLED``. + + If this field is set, it overrides the field names set in + [ServingConfig.geo_search_query_detection_field_names][google.cloud.discoveryengine.v1beta.ServingConfig.geo_search_query_detection_field_names]. + """ + + class FilterExtractionCondition(proto.Enum): + r"""Enum describing under which condition filter extraction + should occur. + + Values: + CONDITION_UNSPECIFIED (0): + Server behavior defaults to [Condition.DISABLED][]. + DISABLED (1): + Disables NL filter extraction. + ENABLED (2): + Enables NL filter extraction. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + filter_extraction_condition: "SearchRequest.NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition", + ) + geo_search_query_detection_field_names: MutableSequence[ + str + ] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class SearchAsYouTypeSpec(proto.Message): + r"""Specification for search as you type in search requests. + + Attributes: + condition (google.cloud.discoveryengine_v1beta.types.SearchRequest.SearchAsYouTypeSpec.Condition): + The condition under which search as you type should occur. + Default to + [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.SearchAsYouTypeSpec.Condition.DISABLED]. + """ + + class Condition(proto.Enum): + r"""Enum describing under which condition search as you type + should occur. + + Values: + CONDITION_UNSPECIFIED (0): + Server behavior defaults to + [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.SearchAsYouTypeSpec.Condition.DISABLED]. + DISABLED (1): + Disables Search As You Type. + ENABLED (2): + Enables Search As You Type. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + condition: "SearchRequest.SearchAsYouTypeSpec.Condition" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.SearchAsYouTypeSpec.Condition", + ) + + class SessionSpec(proto.Message): + r"""Session specification. + + Multi-turn Search feature is currently at private GA stage. + Please use v1alpha or v1beta version instead before we launch + this feature to public GA. Or ask for allowlisting through + Google Support team. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + query_id (str): + If set, the search result gets stored to the "turn" + specified by this query ID. + + Example: Let's say the session looks like this: session { + name: ".../sessions/xxx" turns { query { text: "What is + foo?" query_id: ".../questions/yyy" } answer: "Foo is ..." } + turns { query { text: "How about bar then?" query_id: + ".../questions/zzz" } } } + + The user can call /search API with a request like this: + + :: + + session: ".../sessions/xxx" + session_spec { query_id: ".../questions/zzz" } + + Then, the API stores the search result, associated with the + last turn. The stored search result can be used by a + subsequent /answer API call (with the session ID and the + query ID specified). Also, it is possible to call /search + and /answer in parallel with the same session ID & query ID. + search_result_persistence_count (int): + The number of top search results to persist. The persisted + search results can be used for the subsequent /answer api + call. + + This field is simliar to the ``summary_result_count`` field + in + [SearchRequest.ContentSearchSpec.SummarySpec.summary_result_count][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.summary_result_count]. + + At most 10 results for documents mode, or 50 for chunks + mode. + + This field is a member of `oneof`_ ``_search_result_persistence_count``. + """ + + query_id: str = proto.Field( + proto.STRING, + number=1, + ) + search_result_persistence_count: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.PersonalizationSpec.Mode): + The personalization mode of the search request. Defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + + class Mode(proto.Enum): + r"""The personalization mode of each search request. + + Values: + MODE_UNSPECIFIED (0): + Default value. In this case, server behavior defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + AUTO (1): + Personalization is enabled if data quality + requirements are met. + DISABLED (2): + Disable personalization. + """ + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode: "SearchRequest.PersonalizationSpec.Mode" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.PersonalizationSpec.Mode", + ) + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + branch: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + image_query: ImageQuery = proto.Field( + proto.MESSAGE, + number=19, + message=ImageQuery, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + offset: int = proto.Field( + proto.INT32, + number=6, + ) + one_box_page_size: int = proto.Field( + proto.INT32, + number=47, + ) + data_store_specs: MutableSequence[DataStoreSpec] = proto.RepeatedField( + proto.MESSAGE, + number=32, + message=DataStoreSpec, + ) + filter: str = proto.Field( + proto.STRING, + number=7, + ) + canonical_filter: str = proto.Field( + proto.STRING, + number=29, + ) + order_by: str = proto.Field( + proto.STRING, + number=8, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=21, + message=common.UserInfo, + ) + language_code: str = proto.Field( + proto.STRING, + number=35, + ) + region_code: str = proto.Field( + proto.STRING, + number=36, + ) + facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=FacetSpec, + ) + boost_spec: BoostSpec = proto.Field( + proto.MESSAGE, + number=10, + message=BoostSpec, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message=struct_pb2.Value, + ) + query_expansion_spec: QueryExpansionSpec = proto.Field( + proto.MESSAGE, + number=13, + message=QueryExpansionSpec, + ) + spell_correction_spec: SpellCorrectionSpec = proto.Field( + proto.MESSAGE, + number=14, + message=SpellCorrectionSpec, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=15, + ) + content_search_spec: ContentSearchSpec = proto.Field( + proto.MESSAGE, + number=24, + message=ContentSearchSpec, + ) + embedding_spec: EmbeddingSpec = proto.Field( + proto.MESSAGE, + number=23, + message=EmbeddingSpec, + ) + ranking_expression: str = proto.Field( + proto.STRING, + number=26, + ) + ranking_expression_backend: RankingExpressionBackend = proto.Field( + proto.ENUM, + number=53, + enum=RankingExpressionBackend, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=20, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=22, + ) + natural_language_query_understanding_spec: NaturalLanguageQueryUnderstandingSpec = ( + proto.Field( + proto.MESSAGE, + number=28, + message=NaturalLanguageQueryUnderstandingSpec, + ) + ) + search_as_you_type_spec: SearchAsYouTypeSpec = proto.Field( + proto.MESSAGE, + number=31, + message=SearchAsYouTypeSpec, + ) + session: str = proto.Field( + proto.STRING, + number=41, + ) + session_spec: SessionSpec = proto.Field( + proto.MESSAGE, + number=42, + message=SessionSpec, + ) + relevance_threshold: RelevanceThreshold = proto.Field( + proto.ENUM, + number=44, + enum=RelevanceThreshold, + ) + personalization_spec: PersonalizationSpec = proto.Field( + proto.MESSAGE, + number=46, + message=PersonalizationSpec, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): + A list of matched documents. The order + represents the ranking. + facets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Facet]): + Results of facets requested by user. + guided_search_result (google.cloud.discoveryengine_v1beta.types.SearchResponse.GuidedSearchResult): + Guided search result. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.discoveryengine.v1beta.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.discoveryengine.v1beta.SearchResponse.total_size] + that matches. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + logs resulting from this search, which enables accurate + attribution of search model performance. This also helps to + identify a request during the customer support scenarios. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.discoveryengine.v1beta.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.discoveryengine.v1beta.SearchResponse.attribution_token] + are set in the response. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.discoveryengine.v1beta.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query is + used for search. + summary (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary): + A summary as part of the search results. This field is only + returned if + [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.summary_spec] + is set. + applied_controls (MutableSequence[str]): + Controls applied as part of the Control + service. + geo_search_debug_info (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.GeoSearchDebugInfo]): + + query_expansion_info (google.cloud.discoveryengine_v1beta.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + natural_language_query_understanding_info (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo): + Natural language query understanding + information for the returned results. + session_info (google.cloud.discoveryengine_v1beta.types.SearchResponse.SessionInfo): + Session information. + + Only set if + [SearchRequest.session][google.cloud.discoveryengine.v1beta.SearchRequest.session] + is provided. See its description for more details. + one_box_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.OneBoxResult]): + A list of One Box results. There can be + multiple One Box results of different types. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Document.id][google.cloud.discoveryengine.v1beta.Document.id] + of the searched + [Document][google.cloud.discoveryengine.v1beta.Document]. + document (google.cloud.discoveryengine_v1beta.types.Document): + The document data snippet in the search response. Only + fields that are marked as ``retrievable`` are populated. + chunk (google.cloud.discoveryengine_v1beta.types.Chunk): + The chunk data in the search response if the + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS]. + model_scores (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.DoubleList]): + Google provided available scores. + rank_signals (google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult.RankSignals): + A set of ranking signals associated with the + result. + """ + + class RankSignals(proto.Message): + r"""A set of ranking signals. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + keyword_similarity_score (float): + Keyword matching adjustment. + + This field is a member of `oneof`_ ``_keyword_similarity_score``. + relevance_score (float): + Semantic relevance adjustment. + + This field is a member of `oneof`_ ``_relevance_score``. + semantic_similarity_score (float): + Semantic similarity adjustment. + + This field is a member of `oneof`_ ``_semantic_similarity_score``. + pctr_rank (float): + Predicted conversion rate adjustment as a + rank. + + This field is a member of `oneof`_ ``_pctr_rank``. + topicality_rank (float): + Topicality adjustment as a rank. + + This field is a member of `oneof`_ ``_topicality_rank``. + document_age (float): + Age of the document in hours. + + This field is a member of `oneof`_ ``_document_age``. + boosting_factor (float): + Combined custom boosts for a doc. + + This field is a member of `oneof`_ ``_boosting_factor``. + default_rank (float): + The default rank of the result. + custom_signals (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult.RankSignals.CustomSignal]): + A list of custom clearbox signals. + """ + + class CustomSignal(proto.Message): + r"""Custom clearbox signal represented by name and value pair. + + Attributes: + name (str): + Name of the signal. + value (float): + Float value representing the ranking signal + (e.g. 1.25 for BM25). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: float = proto.Field( + proto.FLOAT, + number=2, + ) + + keyword_similarity_score: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + relevance_score: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + semantic_similarity_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + pctr_rank: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + topicality_rank: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + document_age: float = proto.Field( + proto.FLOAT, + number=7, + optional=True, + ) + boosting_factor: float = proto.Field( + proto.FLOAT, + number=8, + optional=True, + ) + default_rank: float = proto.Field( + proto.FLOAT, + number=32, + ) + custom_signals: MutableSequence[ + "SearchResponse.SearchResult.RankSignals.CustomSignal" + ] = proto.RepeatedField( + proto.MESSAGE, + number=33, + message="SearchResponse.SearchResult.RankSignals.CustomSignal", + ) + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + chunk: gcd_chunk.Chunk = proto.Field( + proto.MESSAGE, + number=18, + message=gcd_chunk.Chunk, + ) + model_scores: MutableMapping[str, common.DoubleList] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=common.DoubleList, + ) + rank_signals: "SearchResponse.SearchResult.RankSignals" = proto.Field( + proto.MESSAGE, + number=7, + message="SearchResponse.SearchResult.RankSignals", + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. For example, ``"colors"`` or + ``"price"``. It matches + [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key]. + values (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Text value of a facet, such as "Black" for + facet "colors". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.discoveryengine_v1beta.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". It matches + [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.intervals]. + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + oneof="facet_value", + ) + interval: common.Interval = proto.Field( + proto.MESSAGE, + number=2, + oneof="facet_value", + message=common.Interval, + ) + count: int = proto.Field( + proto.INT64, + number=3, + ) + + key: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence[ + "SearchResponse.Facet.FacetValue" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SearchResponse.Facet.FacetValue", + ) + dynamic_facet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GuidedSearchResult(proto.Message): + r"""Guided search result. The guided search helps user to refine + the search results and narrow down to the real needs from a + broaded search results. + + Attributes: + refinement_attributes (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.GuidedSearchResult.RefinementAttribute]): + A list of ranked refinement attributes. + follow_up_questions (MutableSequence[str]): + Suggested follow-up questions. + """ + + class RefinementAttribute(proto.Message): + r"""Useful attribute for search result refinements. + + Attributes: + attribute_key (str): + Attribute key used to refine the results. For example, + ``"movie_type"``. + attribute_value (str): + Attribute value used to refine the results. For example, + ``"drama"``. + """ + + attribute_key: str = proto.Field( + proto.STRING, + number=1, + ) + attribute_value: str = proto.Field( + proto.STRING, + number=2, + ) + + refinement_attributes: MutableSequence[ + "SearchResponse.GuidedSearchResult.RefinementAttribute" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchResponse.GuidedSearchResult.RefinementAttribute", + ) + follow_up_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Summary(proto.Message): + r"""Summary of the top N search results specified by the summary + spec. + + Attributes: + summary_text (str): + The summary content. + summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SummarySkippedReason]): + Additional summary-skipped reasons. This + provides the reason for ignored cases. If + nothing is skipped, this field is not set. + safety_attributes (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SafetyAttributes): + A collection of Safety Attribute categories + and their associated confidence scores. + summary_with_metadata (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SummaryWithMetadata): + Summary with metadata information. + """ + + class SummarySkippedReason(proto.Enum): + r"""An Enum for summary-skipped reasons. + + Values: + SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): + Default value. The summary skipped reason is + not specified. + ADVERSARIAL_QUERY_IGNORED (1): + The adversarial query ignored case. + + Only used when + [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] + is set to ``true``. + NON_SUMMARY_SEEKING_QUERY_IGNORED (2): + The non-summary seeking query ignored case. + + Google skips the summary if the query is chit chat. Only + used when + [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] + is set to ``true``. + OUT_OF_DOMAIN_QUERY_IGNORED (3): + The out-of-domain query ignored case. + + Google skips the summary if there are no + high-relevance search results. For example, the + data store contains facts about company A but + the user query is asking questions about company + B. + POTENTIAL_POLICY_VIOLATION (4): + The potential policy violation case. + + Google skips the summary if there is a potential + policy violation detected. This includes content + that may be violent or toxic. + LLM_ADDON_NOT_ENABLED (5): + The LLM addon not enabled case. + + Google skips the summary if the LLM addon is not + enabled. + NO_RELEVANT_CONTENT (6): + The no relevant content case. + + Google skips the summary if there is no relevant + content in the retrieved search results. + JAIL_BREAKING_QUERY_IGNORED (7): + The jail-breaking query ignored case. + + For example, "Reply in the tone of a competing company's + CEO". Only used when + [SearchRequest.ContentSearchSpec.SummarySpec.ignore_jail_breaking_query] + is set to ``true``. + CUSTOMER_POLICY_VIOLATION (8): + The customer policy violation case. + + Google skips the summary if there is a customer + policy violation detected. The policy is defined + by the customer. + NON_SUMMARY_SEEKING_QUERY_IGNORED_V2 (9): + The non-answer seeking query ignored case. + + Google skips the summary if the query doesn't have clear + intent. Only used when + [SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_answer_seeking_query] + is set to ``true``. + """ + SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 + ADVERSARIAL_QUERY_IGNORED = 1 + NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 + OUT_OF_DOMAIN_QUERY_IGNORED = 3 + POTENTIAL_POLICY_VIOLATION = 4 + LLM_ADDON_NOT_ENABLED = 5 + NO_RELEVANT_CONTENT = 6 + JAIL_BREAKING_QUERY_IGNORED = 7 + CUSTOMER_POLICY_VIOLATION = 8 + NON_SUMMARY_SEEKING_QUERY_IGNORED_V2 = 9 + + class SafetyAttributes(proto.Message): + r"""Safety Attribute categories and their associated confidence + scores. + + Attributes: + categories (MutableSequence[str]): + The display names of Safety Attribute + categories associated with the generated + content. Order matches the Scores. + scores (MutableSequence[float]): + The confidence scores of the each category, + higher value means higher confidence. Order + matches the Categories. + """ + + categories: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + scores: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + class CitationMetadata(proto.Message): + r"""Citation metadata. + + Attributes: + citations (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.Citation]): + Citations for segments. + """ + + citations: MutableSequence[ + "SearchResponse.Summary.Citation" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchResponse.Summary.Citation", + ) + + class Citation(proto.Message): + r"""Citation info for a segment. + + Attributes: + start_index (int): + Index indicates the start of the segment, + measured in bytes/unicode. + end_index (int): + End of the attributed segment, exclusive. + sources (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.CitationSource]): + Citation sources for the attributed segment. + """ + + start_index: int = proto.Field( + proto.INT64, + number=1, + ) + end_index: int = proto.Field( + proto.INT64, + number=2, + ) + sources: MutableSequence[ + "SearchResponse.Summary.CitationSource" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SearchResponse.Summary.CitationSource", + ) + + class CitationSource(proto.Message): + r"""Citation source. + + Attributes: + reference_index (int): + Document reference index from + SummaryWithMetadata.references. It is 0-indexed and the + value will be zero if the reference_index is not set + explicitly. + """ + + reference_index: int = proto.Field( + proto.INT64, + number=4, + ) + + class Reference(proto.Message): + r"""Document reference. + + Attributes: + title (str): + Title of the document. + document (str): + Required. + [Document.name][google.cloud.discoveryengine.v1beta.Document.name] + of the document. Full resource name of the referenced + document, in the format + ``projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*``. + uri (str): + Cloud Storage or HTTP uri for the document. + chunk_contents (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.Reference.ChunkContent]): + List of cited chunk contents derived from + document content. + """ + + class ChunkContent(proto.Message): + r"""Chunk content. + + Attributes: + content (str): + Chunk textual content. + page_identifier (str): + Page identifier. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + page_identifier: str = proto.Field( + proto.STRING, + number=2, + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + document: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + chunk_contents: MutableSequence[ + "SearchResponse.Summary.Reference.ChunkContent" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="SearchResponse.Summary.Reference.ChunkContent", + ) + + class SummaryWithMetadata(proto.Message): + r"""Summary with metadata information. + + Attributes: + summary (str): + Summary text with no citation information. + citation_metadata (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.CitationMetadata): + Citation metadata for given summary. + references (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.Reference]): + Document References. + """ + + summary: str = proto.Field( + proto.STRING, + number=1, + ) + citation_metadata: "SearchResponse.Summary.CitationMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="SearchResponse.Summary.CitationMetadata", + ) + references: MutableSequence[ + "SearchResponse.Summary.Reference" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SearchResponse.Summary.Reference", + ) + + summary_text: str = proto.Field( + proto.STRING, + number=1, + ) + summary_skipped_reasons: MutableSequence[ + "SearchResponse.Summary.SummarySkippedReason" + ] = proto.RepeatedField( + proto.ENUM, + number=2, + enum="SearchResponse.Summary.SummarySkippedReason", + ) + safety_attributes: "SearchResponse.Summary.SafetyAttributes" = proto.Field( + proto.MESSAGE, + number=3, + message="SearchResponse.Summary.SafetyAttributes", + ) + summary_with_metadata: "SearchResponse.Summary.SummaryWithMetadata" = ( + proto.Field( + proto.MESSAGE, + number=4, + message="SearchResponse.Summary.SummaryWithMetadata", + ) + ) + + class GeoSearchDebugInfo(proto.Message): + r"""Debug information specifically related to forward geocoding + issues arising from Geolocation Search. + + Attributes: + original_address_query (str): + The address from which forward geocoding + ingestion produced issues. + error_message (str): + The error produced. + """ + + original_address_query: str = proto.Field( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query: bool = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count: int = proto.Field( + proto.INT64, + number=2, + ) + + class NaturalLanguageQueryUnderstandingInfo(proto.Message): + r"""Information describing what natural language understanding + was done on the input query. + + Attributes: + extracted_filters (str): + The filters that were extracted from the + input query. + rewritten_query (str): + Rewritten input query minus the extracted + filters. + structured_extracted_filter (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter): + The filters that were extracted from the + input query represented in a structured form. + """ + + class StructuredExtractedFilter(proto.Message): + r"""The filters that were extracted from the input query + represented in a structured form. + + Attributes: + expression (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression): + The expression denoting the filter that was + extracted from the input query in a structured + form. It can be a simple expression denoting a + single string, numerical or geolocation + constraint or a compound expression which is a + combination of multiple expressions connected + using logical (OR and AND) operators. + """ + + class StringConstraint(proto.Message): + r"""Constraint expression of a string field. + + Attributes: + field_name (str): + Name of the string field as defined in the + schema. + values (MutableSequence[str]): + Values of the string field. The record will + only be returned if the field value matches one + of the values specified here. + query_segment (str): + Identifies the keywords within the search + query that match a filter. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + query_segment: str = proto.Field( + proto.STRING, + number=3, + ) + + class NumberConstraint(proto.Message): + r"""Constraint expression of a number field. Example: price < + 100. + + Attributes: + field_name (str): + Name of the numerical field as defined in the + schema. + comparison (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint.Comparison): + The comparison operation performed between + the field value and the value specified in the + constraint. + value (float): + The value specified in the numerical + constraint. + query_segment (str): + Identifies the keywords within the search + query that match a filter. + """ + + class Comparison(proto.Enum): + r"""The comparison operation that was performed. + + Values: + COMPARISON_UNSPECIFIED (0): + Undefined comparison operator. + EQUALS (1): + Denotes equality ``=`` operator. + LESS_THAN_EQUALS (2): + Denotes less than or equal to ``<=`` operator. + LESS_THAN (3): + Denotes less than ``<`` operator. + GREATER_THAN_EQUALS (4): + Denotes greater than or equal to ``>=`` operator. + GREATER_THAN (5): + Denotes greater than ``>`` operator. + """ + COMPARISON_UNSPECIFIED = 0 + EQUALS = 1 + LESS_THAN_EQUALS = 2 + LESS_THAN = 3 + GREATER_THAN_EQUALS = 4 + GREATER_THAN = 5 + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + comparison: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint.Comparison" = proto.Field( + proto.ENUM, + number=2, + enum="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint.Comparison", + ) + value: float = proto.Field( + proto.DOUBLE, + number=3, + ) + query_segment: str = proto.Field( + proto.STRING, + number=4, + ) + + class GeolocationConstraint(proto.Message): + r"""Constraint of a geolocation field. + Name of the geolocation field as defined in the schema. + + Attributes: + field_name (str): + The name of the geolocation field as defined + in the schema. + address (str): + The reference address that was inferred from + the input query. The proximity of the reference + address to the geolocation field will be used to + filter the results. + latitude (float): + The latitude of the geolocation inferred from + the input query. + longitude (float): + The longitude of the geolocation inferred + from the input query. + radius_in_meters (float): + The radius in meters around the address. The + record is returned if the location of the + geolocation field is within the radius. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + address: str = proto.Field( + proto.STRING, + number=2, + ) + latitude: float = proto.Field( + proto.DOUBLE, + number=4, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=5, + ) + radius_in_meters: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class AndExpression(proto.Message): + r"""Logical ``And`` operator. + + Attributes: + expressions (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression]): + The expressions that were ANDed together. + """ + + expressions: MutableSequence[ + "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression", + ) + + class OrExpression(proto.Message): + r"""Logical ``Or`` operator. + + Attributes: + expressions (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression]): + The expressions that were ORed together. + """ + + expressions: MutableSequence[ + "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression", + ) + + class Expression(proto.Message): + r"""The expression denoting the filter that was extracted from + the input query. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_constraint (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.StringConstraint): + String constraint expression. + + This field is a member of `oneof`_ ``expr``. + number_constraint (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint): + Numerical constraint expression. + + This field is a member of `oneof`_ ``expr``. + geolocation_constraint (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.GeolocationConstraint): + Geolocation constraint expression. + + This field is a member of `oneof`_ ``expr``. + and_expr (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.AndExpression): + Logical "And" compound operator connecting + multiple expressions. + + This field is a member of `oneof`_ ``expr``. + or_expr (google.cloud.discoveryengine_v1beta.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.OrExpression): + Logical "Or" compound operator connecting + multiple expressions. + + This field is a member of `oneof`_ ``expr``. + """ + + string_constraint: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.StringConstraint" = proto.Field( + proto.MESSAGE, + number=1, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.StringConstraint", + ) + number_constraint: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint" = proto.Field( + proto.MESSAGE, + number=2, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint", + ) + geolocation_constraint: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.GeolocationConstraint" = proto.Field( + proto.MESSAGE, + number=3, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.GeolocationConstraint", + ) + and_expr: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.AndExpression" = proto.Field( + proto.MESSAGE, + number=4, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.AndExpression", + ) + or_expr: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.OrExpression" = proto.Field( + proto.MESSAGE, + number=5, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.OrExpression", + ) + + expression: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression" = proto.Field( + proto.MESSAGE, + number=1, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression", + ) + + extracted_filters: str = proto.Field( + proto.STRING, + number=1, + ) + rewritten_query: str = proto.Field( + proto.STRING, + number=2, + ) + structured_extracted_filter: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter" = proto.Field( + proto.MESSAGE, + number=3, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter", + ) + + class SessionInfo(proto.Message): + r"""Information about the session. + + Attributes: + name (str): + Name of the session. If the auto-session mode is used (when + [SearchRequest.session][google.cloud.discoveryengine.v1beta.SearchRequest.session] + ends with "-"), this field holds the newly generated session + name. + query_id (str): + Query ID that corresponds to this search API + call. One session can have multiple turns, each + with a unique query ID. + + By specifying the session name and this query ID + in the Answer API call, the answer generation + happens in the context of the search results + from this search call. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query_id: str = proto.Field( + proto.STRING, + number=2, + ) + + class OneBoxResult(proto.Message): + r"""OneBoxResult is a holder for all results of specific type + that we want to display in UI differently. + + Attributes: + one_box_type (google.cloud.discoveryengine_v1beta.types.SearchResponse.OneBoxResult.OneBoxType): + The type of One Box result. + search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): + The search results for this One Box. + """ + + class OneBoxType(proto.Enum): + r"""The type of One Box result. + + Values: + ONE_BOX_TYPE_UNSPECIFIED (0): + Default value. Should not be used. + PEOPLE (1): + One Box result contains people results. + ORGANIZATION (2): + One Box result contains organization results. + SLACK (3): + One Box result contains slack results. + KNOWLEDGE_GRAPH (4): + One Box result contains Knowledge Graph + search responses. + """ + ONE_BOX_TYPE_UNSPECIFIED = 0 + PEOPLE = 1 + ORGANIZATION = 2 + SLACK = 3 + KNOWLEDGE_GRAPH = 4 + + one_box_type: "SearchResponse.OneBoxResult.OneBoxType" = proto.Field( + proto.ENUM, + number=1, + enum="SearchResponse.OneBoxResult.OneBoxType", + ) + search_results: MutableSequence[ + "SearchResponse.SearchResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SearchResponse.SearchResult", + ) + + @property + def raw_page(self): + return self + + results: MutableSequence[SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets: MutableSequence[Facet] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + guided_search_result: GuidedSearchResult = proto.Field( + proto.MESSAGE, + number=8, + message=GuidedSearchResult, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=4, + ) + redirect_uri: str = proto.Field( + proto.STRING, + number=12, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_query: str = proto.Field( + proto.STRING, + number=7, + ) + summary: Summary = proto.Field( + proto.MESSAGE, + number=9, + message=Summary, + ) + applied_controls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + geo_search_debug_info: MutableSequence[GeoSearchDebugInfo] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=GeoSearchDebugInfo, + ) + query_expansion_info: QueryExpansionInfo = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionInfo, + ) + natural_language_query_understanding_info: NaturalLanguageQueryUnderstandingInfo = ( + proto.Field( + proto.MESSAGE, + number=15, + message=NaturalLanguageQueryUnderstandingInfo, + ) + ) + session_info: SessionInfo = proto.Field( + proto.MESSAGE, + number=19, + message=SessionInfo, + ) + one_box_results: MutableSequence[OneBoxResult] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=OneBoxResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/search_tuning_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/search_tuning_service.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1b175ba10892a25bb46eb2efea2165a8bbb75a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/search_tuning_service.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import custom_tuning_model, import_config + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "ListCustomModelsRequest", + "ListCustomModelsResponse", + "TrainCustomModelRequest", + "TrainCustomModelResponse", + "TrainCustomModelMetadata", + }, +) + + +class ListCustomModelsRequest(proto.Message): + r"""Request message for + [SearchTuningService.ListCustomModels][google.cloud.discoveryengine.v1beta.SearchTuningService.ListCustomModels] + method. + + Attributes: + data_store (str): + Required. The resource name of the parent Data Store, such + as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. + This field is used to identify the data store where to fetch + the models from. + """ + + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCustomModelsResponse(proto.Message): + r"""Response message for + [SearchTuningService.ListCustomModels][google.cloud.discoveryengine.v1beta.SearchTuningService.ListCustomModels] + method. + + Attributes: + models (MutableSequence[google.cloud.discoveryengine_v1beta.types.CustomTuningModel]): + List of custom tuning models. + """ + + models: MutableSequence[ + custom_tuning_model.CustomTuningModel + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=custom_tuning_model.CustomTuningModel, + ) + + +class TrainCustomModelRequest(proto.Message): + r"""Request message for + [SearchTuningService.TrainCustomModel][google.cloud.discoveryengine.v1beta.SearchTuningService.TrainCustomModel] + method. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_training_input (google.cloud.discoveryengine_v1beta.types.TrainCustomModelRequest.GcsTrainingInput): + Cloud Storage training input. + + This field is a member of `oneof`_ ``training_input``. + data_store (str): + Required. The resource name of the Data Store, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. + This field is used to identify the data store where to train + the models. + model_type (str): + Model to be trained. Supported values are: + + - **search-tuning**: Fine tuning the search system based on + data provided. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the data ingestion and training. + model_id (str): + If not provided, a UUID will be generated. + """ + + class GcsTrainingInput(proto.Message): + r"""Cloud Storage training data input. + + Attributes: + corpus_data_path (str): + The Cloud Storage corpus data which could be associated in + train data. The data path format is + ``gs:///``. A newline + delimited jsonl/ndjson file. + + For search-tuning model, each line should have the \_id, + title and text. Example: + ``{"_id": "doc1", title: "relevant doc", "text": "relevant text"}`` + query_data_path (str): + The gcs query data which could be associated in train data. + The data path format is + ``gs:///``. A newline + delimited jsonl/ndjson file. + + For search-tuning model, each line should have the \_id and + text. Example: {"\_id": "query1", "text": "example query"} + train_data_path (str): + Cloud Storage training data path whose format should be + ``gs:///``. The file should + be in tsv format. Each line should have the doc_id and + query_id and score (number). + + For search-tuning model, it should have the query-id + corpus-id score as tsv file header. The score should be a + number in ``[0, inf+)``. The larger the number is, the more + relevant the pair is. Example: + + - ``query-id\tcorpus-id\tscore`` + - ``query1\tdoc1\t1`` + test_data_path (str): + Cloud Storage test data. Same format as train_data_path. If + not provided, a random 80/20 train/test split will be + performed on train_data_path. + """ + + corpus_data_path: str = proto.Field( + proto.STRING, + number=1, + ) + query_data_path: str = proto.Field( + proto.STRING, + number=2, + ) + train_data_path: str = proto.Field( + proto.STRING, + number=3, + ) + test_data_path: str = proto.Field( + proto.STRING, + number=4, + ) + + gcs_training_input: GcsTrainingInput = proto.Field( + proto.MESSAGE, + number=2, + oneof="training_input", + message=GcsTrainingInput, + ) + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + model_type: str = proto.Field( + proto.STRING, + number=3, + ) + error_config: import_config.ImportErrorConfig = proto.Field( + proto.MESSAGE, + number=4, + message=import_config.ImportErrorConfig, + ) + model_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class TrainCustomModelResponse(proto.Message): + r"""Response of the + [TrainCustomModelRequest][google.cloud.discoveryengine.v1beta.TrainCustomModelRequest]. + This message is returned by the + google.longrunning.Operations.response field. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the data. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + Echoes the destination for the complete + errors in the request if set. + model_status (str): + The trained model status. Possible values are: + + - **bad-data**: The training data quality is bad. + - **no-improvement**: Tuning didn't improve performance. + Won't deploy. + - **in-progress**: Model training job creation is in + progress. + - **training**: Model is actively training. + - **evaluating**: The model is evaluating trained metrics. + - **indexing**: The model trained metrics are indexing. + - **ready**: The model is ready for serving. + metrics (MutableMapping[str, float]): + The metrics of the trained model. + model_name (str): + Fully qualified name of the + CustomTuningModel. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: import_config.ImportErrorConfig = proto.Field( + proto.MESSAGE, + number=2, + message=import_config.ImportErrorConfig, + ) + model_status: str = proto.Field( + proto.STRING, + number=3, + ) + metrics: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=4, + ) + model_name: str = proto.Field( + proto.STRING, + number=5, + ) + + +class TrainCustomModelMetadata(proto.Message): + r"""Metadata related to the progress of the TrainCustomModel + operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/serving_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/serving_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c518f8a9b3f958f8dfaadbb6b3f45d62f5650994 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/serving_config.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common, search_service + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "ServingConfig", + }, +) + + +class ServingConfig(proto.Message): + r"""Configures metadata that is used to generate serving time + results (e.g. search results or recommendation predictions). The + ServingConfig is passed in the search and predict request and + generates results. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + media_config (google.cloud.discoveryengine_v1beta.types.ServingConfig.MediaConfig): + The MediaConfig of the serving configuration. + + This field is a member of `oneof`_ ``vertical_config``. + generic_config (google.cloud.discoveryengine_v1beta.types.ServingConfig.GenericConfig): + The GenericConfig of the serving + configuration. + + This field is a member of `oneof`_ ``vertical_config``. + name (str): + Immutable. Fully qualified name + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}/servingConfigs/{serving_config_id}`` + display_name (str): + Required. The human readable serving config display name. + Used in Discovery UI. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + solution_type (google.cloud.discoveryengine_v1beta.types.SolutionType): + Required. Immutable. Specifies the solution + type that a serving config can be associated + with. + model_id (str): + The id of the model to use at serving time. Currently only + RecommendationModels are supported. Can be changed but only + to a compatible model (e.g. others-you-may-like CTR to + others-you-may-like CVR). + + Required when + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + diversity_level (str): + How much diversity to use in recommendation model results + e.g. ``medium-diversity`` or ``high-diversity``. Currently + supported values: + + - ``no-diversity`` + - ``low-diversity`` + - ``medium-diversity`` + - ``high-diversity`` + - ``auto-diversity`` + + If not specified, we choose default based on recommendation + model type. Default value: ``no-diversity``. + + Can only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + embedding_config (google.cloud.discoveryengine_v1beta.types.EmbeddingConfig): + Bring your own embedding config. The config is used for + search semantic retrieval. The retrieval is based on the dot + product of + [SearchRequest.EmbeddingSpec.EmbeddingVector.vector][google.cloud.discoveryengine.v1beta.SearchRequest.EmbeddingSpec.EmbeddingVector.vector] + and the document embeddings that are provided by this + EmbeddingConfig. If + [SearchRequest.EmbeddingSpec.EmbeddingVector.vector][google.cloud.discoveryengine.v1beta.SearchRequest.EmbeddingSpec.EmbeddingVector.vector] + is provided, it overrides this + [ServingConfig.embedding_config][google.cloud.discoveryengine.v1beta.ServingConfig.embedding_config]. + ranking_expression (str): + The ranking expression controls the customized ranking on + retrieval documents. To leverage this, document embedding is + required. The ranking expression setting in ServingConfig + applies to all search requests served by the serving config. + However, if + [SearchRequest.ranking_expression][google.cloud.discoveryengine.v1beta.SearchRequest.ranking_expression] + is specified, it overrides the ServingConfig ranking + expression. + + The ranking expression is a single function or multiple + functions that are joined by "+". + + - ranking_expression = function, { " + ", function }; + + Supported functions: + + - double \* relevance_score + - double \* dotProduct(embedding_field_path) + + Function variables: + + - ``relevance_score``: pre-defined keywords, used for + measure relevance between query and document. + - ``embedding_field_path``: the document embedding field + used with query embedding vector. + - ``dotProduct``: embedding function between + embedding_field_path and query embedding vector. + + Example ranking expression: + + :: + + If document has an embedding field doc_embedding, the ranking expression + could be `0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)`. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. ServingConfig created timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. ServingConfig updated timestamp. + filter_control_ids (MutableSequence[str]): + Filter controls to use in serving path. + All triggered filter controls will be applied. + Filter controls must be in the same data store + as the serving config. Maximum of 20 filter + controls. + boost_control_ids (MutableSequence[str]): + Boost controls to use in serving path. + All triggered boost controls will be applied. + Boost controls must be in the same data store as + the serving config. Maximum of 20 boost + controls. + redirect_control_ids (MutableSequence[str]): + IDs of the redirect controls. Only the first triggered + redirect action is applied, even if multiple apply. Maximum + number of specifications is 100. + + Can only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + synonyms_control_ids (MutableSequence[str]): + Condition synonyms specifications. If multiple synonyms + conditions match, all matching synonyms controls in the list + will execute. Maximum number of specifications is 100. + + Can only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + oneway_synonyms_control_ids (MutableSequence[str]): + Condition oneway synonyms specifications. If multiple oneway + synonyms conditions match, all matching oneway synonyms + controls in the list will execute. Maximum number of + specifications is 100. + + Can only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + dissociate_control_ids (MutableSequence[str]): + Condition do not associate specifications. If multiple do + not associate conditions match, all matching do not + associate controls in the list will execute. Order does not + matter. Maximum number of specifications is 100. + + Can only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + replacement_control_ids (MutableSequence[str]): + Condition replacement specifications. Applied according to + the order in the list. A previously replaced term can not be + re-replaced. Maximum number of specifications is 100. + + Can only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_SEARCH]. + ignore_control_ids (MutableSequence[str]): + Condition ignore specifications. If multiple + ignore conditions match, all matching ignore + controls in the list will execute. + Order does not matter. + Maximum number of specifications is 100. + personalization_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization spec. + + Notice that if both + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec] + and + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + are set, + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + overrides + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec]. + """ + + class MediaConfig(proto.Message): + r"""Specifies the configurations needed for Media Discovery. Currently + we support: + + - ``demote_content_watched``: Threshold for watched content + demotion. Customers can specify if using watched content demotion + or use viewed detail page. Using the content watched demotion, + customers need to specify the watched minutes or percentage + exceeds the threshold, the content will be demoted in the + recommendation result. + - ``promote_fresh_content``: cutoff days for fresh content + promotion. Customers can specify if using content freshness + promotion. If the content was published within the cutoff days, + the content will be promoted in the recommendation result. Can + only be set if + [SolutionType][google.cloud.discoveryengine.v1beta.SolutionType] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content_watched_percentage_threshold (float): + Specifies the content watched percentage threshold for + demotion. Threshold value must be between [0, 1.0] + inclusive. + + This field is a member of `oneof`_ ``demote_content_watched``. + content_watched_seconds_threshold (float): + Specifies the content watched minutes + threshold for demotion. + + This field is a member of `oneof`_ ``demote_content_watched``. + demotion_event_type (str): + Specifies the event type used for demoting recommendation + result. Currently supported values: + + - ``view-item``: Item viewed. + - ``media-play``: Start/resume watching a video, playing a + song, etc. + - ``media-complete``: Finished or stopped midway through a + video, song, etc. + + If unset, watch history demotion will not be applied. + Content freshness demotion will still be applied. + demote_content_watched_past_days (int): + Optional. Specifies the number of days to + look back for demoting watched content. If set + to zero or unset, defaults to the maximum of 365 + days. + content_freshness_cutoff_days (int): + Specifies the content freshness used for + recommendation result. Contents will be demoted + if contents were published for more than content + freshness cutoff days. + """ + + content_watched_percentage_threshold: float = proto.Field( + proto.FLOAT, + number=2, + oneof="demote_content_watched", + ) + content_watched_seconds_threshold: float = proto.Field( + proto.FLOAT, + number=5, + oneof="demote_content_watched", + ) + demotion_event_type: str = proto.Field( + proto.STRING, + number=1, + ) + demote_content_watched_past_days: int = proto.Field( + proto.INT32, + number=37, + ) + content_freshness_cutoff_days: int = proto.Field( + proto.INT32, + number=4, + ) + + class GenericConfig(proto.Message): + r"""Specifies the configurations needed for Generic Discovery.Currently + we support: + + - ``content_search_spec``: configuration for generic content search. + + Attributes: + content_search_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec): + Specifies the expected behavior of content + search. Only valid for content-search enabled + data store. + """ + + content_search_spec: search_service.SearchRequest.ContentSearchSpec = ( + proto.Field( + proto.MESSAGE, + number=1, + message=search_service.SearchRequest.ContentSearchSpec, + ) + ) + + media_config: MediaConfig = proto.Field( + proto.MESSAGE, + number=7, + oneof="vertical_config", + message=MediaConfig, + ) + generic_config: GenericConfig = proto.Field( + proto.MESSAGE, + number=10, + oneof="vertical_config", + message=GenericConfig, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + solution_type: common.SolutionType = proto.Field( + proto.ENUM, + number=3, + enum=common.SolutionType, + ) + model_id: str = proto.Field( + proto.STRING, + number=4, + ) + diversity_level: str = proto.Field( + proto.STRING, + number=5, + ) + embedding_config: common.EmbeddingConfig = proto.Field( + proto.MESSAGE, + number=20, + message=common.EmbeddingConfig, + ) + ranking_expression: str = proto.Field( + proto.STRING, + number=21, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + filter_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + boost_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + redirect_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=14, + ) + synonyms_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + oneway_synonyms_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=16, + ) + dissociate_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=17, + ) + replacement_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=18, + ) + ignore_control_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=19, + ) + personalization_spec: search_service.SearchRequest.PersonalizationSpec = ( + proto.Field( + proto.MESSAGE, + number=25, + message=search_service.SearchRequest.PersonalizationSpec, + ) + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/serving_config_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/serving_config_service.py new file mode 100644 index 0000000000000000000000000000000000000000..2701dec76cc85c345a9aa32ddf63f1a66a6d27a8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/serving_config_service.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + serving_config as gcd_serving_config, +) + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "UpdateServingConfigRequest", + "GetServingConfigRequest", + "ListServingConfigsRequest", + "ListServingConfigsResponse", + }, +) + + +class UpdateServingConfigRequest(proto.Message): + r"""Request for UpdateServingConfig method. + + Attributes: + serving_config (google.cloud.discoveryengine_v1beta.types.ServingConfig): + Required. The ServingConfig to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig] + to update. The following are NOT supported: + + - [ServingConfig.name][google.cloud.discoveryengine.v1beta.ServingConfig.name] + + If not set, all supported fields are updated. + """ + + serving_config: gcd_serving_config.ServingConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_serving_config.ServingConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetServingConfigRequest(proto.Message): + r"""Request for GetServingConfig method. + + Attributes: + name (str): + Required. The resource name of the ServingConfig to get. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServingConfigsRequest(proto.Message): + r"""Request for ListServingConfigs method. + + Attributes: + parent (str): + Required. Full resource name of the parent resource. Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` + page_size (int): + Optional. Maximum number of results to + return. If unspecified, defaults to 100. If a + value greater than 100 is provided, at most 100 + results are returned. + page_token (str): + Optional. A page token, received from a previous + ``ListServingConfigs`` call. Provide this to retrieve the + subsequent page. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServingConfigsResponse(proto.Message): + r"""Response for ListServingConfigs method. + + Attributes: + serving_configs (MutableSequence[google.cloud.discoveryengine_v1beta.types.ServingConfig]): + All the ServingConfigs for a given dataStore. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + serving_configs: MutableSequence[ + gcd_serving_config.ServingConfig + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_serving_config.ServingConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/session.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/session.py new file mode 100644 index 0000000000000000000000000000000000000000..013ee90b77c480ba2ea289795ebb088fba9f95cf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/session.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import answer as gcd_answer + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Session", + "Query", + }, +) + + +class Session(proto.Message): + r"""External session proto definition. + + Attributes: + name (str): + Immutable. Fully qualified name + ``projects/{project}/locations/global/collections/{collection}/engines/{engine}/sessions/*`` + display_name (str): + Optional. The display name of the session. + + This field is used to identify the session in + the UI. By default, the display name is the + first turn query text in the session. + state (google.cloud.discoveryengine_v1beta.types.Session.State): + The state of the session. + user_pseudo_id (str): + A unique identifier for tracking users. + turns (MutableSequence[google.cloud.discoveryengine_v1beta.types.Session.Turn]): + Turns. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the session started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the session finished. + is_pinned (bool): + Optional. Whether the session is pinned, + pinned session will be displayed on the top of + the session list. + """ + + class State(proto.Enum): + r"""Enumeration of the state of the session. + + Values: + STATE_UNSPECIFIED (0): + State is unspecified. + IN_PROGRESS (1): + The session is currently open. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + + class Turn(proto.Message): + r"""Represents a turn, including a query from the user and a + answer from service. + + Attributes: + query (google.cloud.discoveryengine_v1beta.types.Query): + Optional. The user query. May not be set if + this turn is merely regenerating an answer to a + different turn + answer (str): + Optional. The resource name of the answer to + the user query. + Only set if the answer generation (/answer API + call) happened in this turn. + detailed_answer (google.cloud.discoveryengine_v1beta.types.Answer): + Output only. In + [ConversationalSearchService.GetSession][google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetSession] + API, if + [GetSessionRequest.include_answer_details][google.cloud.discoveryengine.v1beta.GetSessionRequest.include_answer_details] + is set to true, this field will be populated when getting + answer query session. + query_config (MutableMapping[str, str]): + Optional. Represents metadata related to the + query config, for example LLM model and version + used, model parameters (temperature, grounding + parameters, etc.). The prefix "google." is + reserved for Google-developed functionality. + """ + + query: "Query" = proto.Field( + proto.MESSAGE, + number=1, + message="Query", + ) + answer: str = proto.Field( + proto.STRING, + number=2, + ) + detailed_answer: gcd_answer.Answer = proto.Field( + proto.MESSAGE, + number=7, + message=gcd_answer.Answer, + ) + query_config: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=16, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=3, + ) + turns: MutableSequence[Turn] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Turn, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + is_pinned: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class Query(proto.Message): + r"""Defines a user inputed query. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Plain text. + + This field is a member of `oneof`_ ``content``. + query_id (str): + Output only. Unique Id for the query. + """ + + text: str = proto.Field( + proto.STRING, + number=2, + oneof="content", + ) + query_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/session_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/session_service.py new file mode 100644 index 0000000000000000000000000000000000000000..589f350cf1e3cc842ad57ab126e05af613a4c9b3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/session_service.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={}, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/site_search_engine.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/site_search_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..87bb9aa78b38a2a256a419bc8e84cce377622f70 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/site_search_engine.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SiteSearchEngine", + "TargetSite", + "SiteVerificationInfo", + "Sitemap", + }, +) + + +class SiteSearchEngine(proto.Message): + r"""SiteSearchEngine captures DataStore level site search + persisting configurations. It is a singleton value per data + store. + + Attributes: + name (str): + The fully qualified resource name of the site search engine. + Format: + ``projects/*/locations/*/dataStores/*/siteSearchEngine`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TargetSite(proto.Message): + r"""A target site for the SiteSearchEngine. + + Attributes: + name (str): + Output only. The fully qualified resource name of the target + site. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}`` + The ``target_site_id`` is system-generated. + provided_uri_pattern (str): + Required. Input only. The user provided URI pattern from + which the ``generated_uri_pattern`` is generated. + type_ (google.cloud.discoveryengine_v1beta.types.TargetSite.Type): + The type of the target site, e.g., whether + the site is to be included or excluded. + exact_match (bool): + Input only. If set to false, a uri_pattern is generated to + include all pages whose address contains the + provided_uri_pattern. If set to true, an uri_pattern is + generated to try to be an exact match of the + provided_uri_pattern or just the specific page if the + provided_uri_pattern is a specific one. provided_uri_pattern + is always normalized to generate the URI pattern to be used + by the search engine. + generated_uri_pattern (str): + Output only. This is system-generated based on the + provided_uri_pattern. + root_domain_uri (str): + Output only. Root domain of the provided_uri_pattern. + site_verification_info (google.cloud.discoveryengine_v1beta.types.SiteVerificationInfo): + Output only. Site ownership and validity + verification status. + indexing_status (google.cloud.discoveryengine_v1beta.types.TargetSite.IndexingStatus): + Output only. Indexing status. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The target site's last updated + time. + failure_reason (google.cloud.discoveryengine_v1beta.types.TargetSite.FailureReason): + Output only. Failure reason. + """ + + class Type(proto.Enum): + r"""Possible target site types. + + Values: + TYPE_UNSPECIFIED (0): + This value is unused. In this case, server behavior defaults + to + [Type.INCLUDE][google.cloud.discoveryengine.v1beta.TargetSite.Type.INCLUDE]. + INCLUDE (1): + Include the target site. + EXCLUDE (2): + Exclude the target site. + """ + TYPE_UNSPECIFIED = 0 + INCLUDE = 1 + EXCLUDE = 2 + + class IndexingStatus(proto.Enum): + r"""Target site indexing status enumeration. + + Values: + INDEXING_STATUS_UNSPECIFIED (0): + Defaults to SUCCEEDED. + PENDING (1): + The target site is in the update queue and + will be picked up by indexing pipeline. + FAILED (2): + The target site fails to be indexed. + SUCCEEDED (3): + The target site has been indexed. + DELETING (4): + The previously indexed target site has been + marked to be deleted. This is a transitioning + state which will resulted in either: + + 1. target site deleted if unindexing is + successful; + 2. state reverts to SUCCEEDED if the unindexing + fails. + """ + INDEXING_STATUS_UNSPECIFIED = 0 + PENDING = 1 + FAILED = 2 + SUCCEEDED = 3 + DELETING = 4 + + class FailureReason(proto.Message): + r"""Site search indexing failure reasons. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + quota_failure (google.cloud.discoveryengine_v1beta.types.TargetSite.FailureReason.QuotaFailure): + Failed due to insufficient quota. + + This field is a member of `oneof`_ ``failure``. + """ + + class QuotaFailure(proto.Message): + r"""Failed due to insufficient quota. + + Attributes: + total_required_quota (int): + This number is an estimation on how much + total quota this project needs to successfully + complete indexing. + """ + + total_required_quota: int = proto.Field( + proto.INT64, + number=1, + ) + + quota_failure: "TargetSite.FailureReason.QuotaFailure" = proto.Field( + proto.MESSAGE, + number=1, + oneof="failure", + message="TargetSite.FailureReason.QuotaFailure", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + provided_uri_pattern: str = proto.Field( + proto.STRING, + number=2, + ) + type_: Type = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + exact_match: bool = proto.Field( + proto.BOOL, + number=6, + ) + generated_uri_pattern: str = proto.Field( + proto.STRING, + number=4, + ) + root_domain_uri: str = proto.Field( + proto.STRING, + number=10, + ) + site_verification_info: "SiteVerificationInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="SiteVerificationInfo", + ) + indexing_status: IndexingStatus = proto.Field( + proto.ENUM, + number=8, + enum=IndexingStatus, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + failure_reason: FailureReason = proto.Field( + proto.MESSAGE, + number=9, + message=FailureReason, + ) + + +class SiteVerificationInfo(proto.Message): + r"""Verification information for target sites in advanced site + search. + + Attributes: + site_verification_state (google.cloud.discoveryengine_v1beta.types.SiteVerificationInfo.SiteVerificationState): + Site verification state indicating the + ownership and validity. + verify_time (google.protobuf.timestamp_pb2.Timestamp): + Latest site verification time. + """ + + class SiteVerificationState(proto.Enum): + r"""Site verification state. + + Values: + SITE_VERIFICATION_STATE_UNSPECIFIED (0): + Defaults to VERIFIED. + VERIFIED (1): + Site ownership verified. + UNVERIFIED (2): + Site ownership pending verification or + verification failed. + EXEMPTED (3): + Site exempt from verification, e.g., a public + website that opens to all. + """ + SITE_VERIFICATION_STATE_UNSPECIFIED = 0 + VERIFIED = 1 + UNVERIFIED = 2 + EXEMPTED = 3 + + site_verification_state: SiteVerificationState = proto.Field( + proto.ENUM, + number=1, + enum=SiteVerificationState, + ) + verify_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Sitemap(proto.Message): + r"""A sitemap for the SiteSearchEngine. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Public URI for the sitemap, e.g. + ``www.example.com/sitemap.xml``. + + This field is a member of `oneof`_ ``feed``. + name (str): + Output only. The fully qualified resource name of the + sitemap. + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/sitemaps/*`` + The ``sitemap_id`` suffix is system-generated. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The sitemap's creation time. + """ + + uri: str = proto.Field( + proto.STRING, + number=2, + oneof="feed", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py new file mode 100644 index 0000000000000000000000000000000000000000..2db134f260368ed0e2fdce5dbe454ef0b3014c0a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py @@ -0,0 +1,1099 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + site_search_engine as gcd_site_search_engine, +) + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetSiteSearchEngineRequest", + "CreateTargetSiteRequest", + "CreateTargetSiteMetadata", + "BatchCreateTargetSitesRequest", + "GetTargetSiteRequest", + "UpdateTargetSiteRequest", + "UpdateTargetSiteMetadata", + "DeleteTargetSiteRequest", + "DeleteTargetSiteMetadata", + "ListTargetSitesRequest", + "ListTargetSitesResponse", + "BatchCreateTargetSiteMetadata", + "BatchCreateTargetSitesResponse", + "CreateSitemapRequest", + "DeleteSitemapRequest", + "FetchSitemapsRequest", + "CreateSitemapMetadata", + "DeleteSitemapMetadata", + "FetchSitemapsResponse", + "EnableAdvancedSiteSearchRequest", + "EnableAdvancedSiteSearchResponse", + "EnableAdvancedSiteSearchMetadata", + "DisableAdvancedSiteSearchRequest", + "DisableAdvancedSiteSearchResponse", + "DisableAdvancedSiteSearchMetadata", + "RecrawlUrisRequest", + "RecrawlUrisResponse", + "RecrawlUrisMetadata", + "BatchVerifyTargetSitesRequest", + "BatchVerifyTargetSitesResponse", + "BatchVerifyTargetSitesMetadata", + "FetchDomainVerificationStatusRequest", + "FetchDomainVerificationStatusResponse", + }, +) + + +class GetSiteSearchEngineRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.GetSiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetSiteSearchEngine] + method. + + Attributes: + name (str): + Required. Resource name of + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + If the caller does not have permission to access the + [SiteSearchEngine], regardless of whether or not it exists, + a PERMISSION_DENIED error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTargetSiteRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.CreateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite] + method. + + Attributes: + parent (str): + Required. Parent resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + target_site (google.cloud.discoveryengine_v1beta.types.TargetSite): + Required. The + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + target_site: gcd_site_search_engine.TargetSite = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_site_search_engine.TargetSite, + ) + + +class CreateTargetSiteMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.CreateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class BatchCreateTargetSitesRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + + Attributes: + parent (str): + Required. The parent resource shared by all TargetSites + being created. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + The parent field in the CreateBookRequest messages must + either be empty or match this field. + requests (MutableSequence[google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest]): + Required. The request message specifying the + resources to create. A maximum of 20 TargetSites + can be created in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["CreateTargetSiteRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CreateTargetSiteRequest", + ) + + +class GetTargetSiteRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.GetTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.GetTargetSite] + method. + + Attributes: + name (str): + Required. Full resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}``. + + If the caller does not have permission to access the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateTargetSiteRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.UpdateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.UpdateTargetSite] + method. + + Attributes: + target_site (google.cloud.discoveryengine_v1beta.types.TargetSite): + Required. The target site to update. If the caller does not + have permission to update the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + to update does not exist, a NOT_FOUND error is returned. + """ + + target_site: gcd_site_search_engine.TargetSite = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_site_search_engine.TargetSite, + ) + + +class UpdateTargetSiteMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.UpdateTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.UpdateTargetSite] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteTargetSiteRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.DeleteTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteTargetSite] + method. + + Attributes: + name (str): + Required. Full resource name of + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}``. + + If the caller does not have permission to access the + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteTargetSiteMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.DeleteTargetSite][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteTargetSite] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListTargetSitesRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + + Attributes: + parent (str): + Required. The parent site search engine resource name, such + as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + + If the caller does not have permission to list + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite]s + under this site search engine, regardless of whether or not + this branch exists, a PERMISSION_DENIED error is returned. + page_size (int): + Requested page size. Server may return fewer items than + requested. If unspecified, server will pick an appropriate + default. The maximum value is 1000; values above 1000 will + be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT error is + returned. + page_token (str): + A page token, received from a previous ``ListTargetSites`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListTargetSites`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTargetSitesResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.ListTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.ListTargetSites] + method. + + Attributes: + target_sites (MutableSequence[google.cloud.discoveryengine_v1beta.types.TargetSite]): + List of TargetSites. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + total_size (int): + The total number of items matching the + request. This will always be populated in the + response. + """ + + @property + def raw_page(self): + return self + + target_sites: MutableSequence[ + gcd_site_search_engine.TargetSite + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_site_search_engine.TargetSite, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class BatchCreateTargetSiteMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class BatchCreateTargetSitesResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.BatchCreateTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites] + method. + + Attributes: + target_sites (MutableSequence[google.cloud.discoveryengine_v1beta.types.TargetSite]): + TargetSites created. + """ + + target_sites: MutableSequence[ + gcd_site_search_engine.TargetSite + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_site_search_engine.TargetSite, + ) + + +class CreateSitemapRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + + Attributes: + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + sitemap (google.cloud.discoveryengine_v1beta.types.Sitemap): + Required. The + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sitemap: gcd_site_search_engine.Sitemap = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_site_search_engine.Sitemap, + ) + + +class DeleteSitemapRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + + Attributes: + name (str): + Required. Full resource name of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], such + as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}``. + + If the caller does not have permission to access the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] does + not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchSitemapsRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + Attributes: + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + matcher (google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest.Matcher): + Optional. If specified, fetches the matching + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s. If + not specified, fetches all + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + """ + + class UrisMatcher(proto.Message): + r"""Matcher for the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s by their + uris. + + Attributes: + uris (MutableSequence[str]): + The [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + uris. + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Matcher(proto.Message): + r"""Matcher for the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s. Currently + only supports uris matcher. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uris_matcher (google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest.UrisMatcher): + Matcher by sitemap URIs. + + This field is a member of `oneof`_ ``matcher``. + """ + + uris_matcher: "FetchSitemapsRequest.UrisMatcher" = proto.Field( + proto.MESSAGE, + number=1, + oneof="matcher", + message="FetchSitemapsRequest.UrisMatcher", + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + matcher: Matcher = proto.Field( + proto.MESSAGE, + number=2, + message=Matcher, + ) + + +class CreateSitemapMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteSitemapMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class FetchSitemapsResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + Attributes: + sitemaps_metadata (MutableSequence[google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse.SitemapMetadata]): + List of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s + fetched. + """ + + class SitemapMetadata(proto.Message): + r"""Contains a [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + and its metadata. + + Attributes: + sitemap (google.cloud.discoveryengine_v1beta.types.Sitemap): + The [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + """ + + sitemap: gcd_site_search_engine.Sitemap = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_site_search_engine.Sitemap, + ) + + sitemaps_metadata: MutableSequence[SitemapMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SitemapMetadata, + ) + + +class EnableAdvancedSiteSearchRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + + Attributes: + site_search_engine (str): + Required. Full resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/{project}/locations/{location}/dataStores/{data_store_id}/siteSearchEngine``. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EnableAdvancedSiteSearchResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + method. + + """ + + +class EnableAdvancedSiteSearchMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DisableAdvancedSiteSearchRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + + Attributes: + site_search_engine (str): + Required. Full resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/{project}/locations/{location}/dataStores/{data_store_id}/siteSearchEngine``. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableAdvancedSiteSearchResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + method. + + """ + + +class DisableAdvancedSiteSearchMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.DisableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DisableAdvancedSiteSearch] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class RecrawlUrisRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + + Attributes: + site_search_engine (str): + Required. Full resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + uris (MutableSequence[str]): + Required. List of URIs to crawl. At most 10K URIs are + supported, otherwise an INVALID_ARGUMENT error is thrown. + Each URI should match at least one + [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] + in ``site_search_engine``. + site_credential (str): + Optional. Full resource name of the [SiteCredential][], such + as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/siteCredentials/*``. + Only set to crawl private URIs. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + site_credential: str = proto.Field( + proto.STRING, + number=5, + ) + + +class RecrawlUrisResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + method. + + Attributes: + failure_samples (MutableSequence[google.cloud.discoveryengine_v1beta.types.RecrawlUrisResponse.FailureInfo]): + Details for a sample of up to 10 ``failed_uris``. + failed_uris (MutableSequence[str]): + URIs that were not crawled before the LRO + terminated. + """ + + class FailureInfo(proto.Message): + r"""Details about why a particular URI failed to be crawled. Each + FailureInfo contains one FailureReason per CorpusType. + + Attributes: + uri (str): + URI that failed to be crawled. + failure_reasons (MutableSequence[google.cloud.discoveryengine_v1beta.types.RecrawlUrisResponse.FailureInfo.FailureReason]): + List of failure reasons by corpus type (e.g. + desktop, mobile). + """ + + class FailureReason(proto.Message): + r"""Details about why crawling failed for a particular + CorpusType, e.g., DESKTOP and MOBILE crawling may fail for + different reasons. + + Attributes: + corpus_type (google.cloud.discoveryengine_v1beta.types.RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType): + DESKTOP, MOBILE, or CORPUS_TYPE_UNSPECIFIED. + error_message (str): + Reason why the URI was not crawled. + """ + + class CorpusType(proto.Enum): + r"""CorpusType for the failed crawling operation. + + Values: + CORPUS_TYPE_UNSPECIFIED (0): + Default value. + DESKTOP (1): + Denotes a crawling attempt for the desktop + version of a page. + MOBILE (2): + Denotes a crawling attempt for the mobile + version of a page. + """ + CORPUS_TYPE_UNSPECIFIED = 0 + DESKTOP = 1 + MOBILE = 2 + + corpus_type: "RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType" = ( + proto.Field( + proto.ENUM, + number=1, + enum="RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType", + ) + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + failure_reasons: MutableSequence[ + "RecrawlUrisResponse.FailureInfo.FailureReason" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="RecrawlUrisResponse.FailureInfo.FailureReason", + ) + + failure_samples: MutableSequence[FailureInfo] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=FailureInfo, + ) + failed_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class RecrawlUrisMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.RecrawlUris] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + invalid_uris (MutableSequence[str]): + Unique URIs in the request that have invalid + format. Sample limited to 1000. + invalid_uris_count (int): + Total number of unique URIs in the request + that have invalid format. + uris_not_matching_target_sites (MutableSequence[str]): + Unique URIs in the request that don't match + any TargetSite in the DataStore, only match + TargetSites that haven't been fully indexed, or + match a TargetSite with type EXCLUDE. Sample + limited to 1000. + uris_not_matching_target_sites_count (int): + Total number of URIs that don't match any + TargetSites. + valid_uris_count (int): + Total number of unique URIs in the request that are not in + invalid_uris. + success_count (int): + Total number of URIs that have been crawled + so far. + pending_count (int): + Total number of URIs that have yet to be + crawled. + quota_exceeded_count (int): + Total number of URIs that were rejected due + to insufficient indexing resources. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + invalid_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + invalid_uris_count: int = proto.Field( + proto.INT32, + number=8, + ) + uris_not_matching_target_sites: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + uris_not_matching_target_sites_count: int = proto.Field( + proto.INT32, + number=10, + ) + valid_uris_count: int = proto.Field( + proto.INT32, + number=4, + ) + success_count: int = proto.Field( + proto.INT32, + number=5, + ) + pending_count: int = proto.Field( + proto.INT32, + number=6, + ) + quota_exceeded_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +class BatchVerifyTargetSitesRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + + Attributes: + parent (str): + Required. The parent resource shared by all TargetSites + being verified. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchVerifyTargetSitesResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + method. + + """ + + +class BatchVerifyTargetSitesMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.BatchVerifyTargetSites][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class FetchDomainVerificationStatusRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + + Attributes: + site_search_engine (str): + Required. The site search engine resource under which we + fetch all the domain verification status. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine``. + page_size (int): + Requested page size. Server may return fewer items than + requested. If unspecified, server will pick an appropriate + default. The maximum value is 1000; values above 1000 will + be coerced to 1000. + + If this field is negative, an INVALID_ARGUMENT error is + returned. + page_token (str): + A page token, received from a previous + ``FetchDomainVerificationStatus`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``FetchDomainVerificationStatus`` must match the call that + provided the page token. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class FetchDomainVerificationStatusResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.FetchDomainVerificationStatus][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchDomainVerificationStatus] + method. + + Attributes: + target_sites (MutableSequence[google.cloud.discoveryengine_v1beta.types.TargetSite]): + List of TargetSites containing the site + verification status. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + total_size (int): + The total number of items matching the + request. This will always be populated in the + response. + """ + + @property + def raw_page(self): + return self + + target_sites: MutableSequence[ + gcd_site_search_engine.TargetSite + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_site_search_engine.TargetSite, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/user_event.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/user_event.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7918c4a605ecf9a4a774f0f762c456fb0e0dd0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/user_event.py @@ -0,0 +1,811 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "UserEvent", + "PageInfo", + "SearchInfo", + "CompletionInfo", + "TransactionInfo", + "DocumentInfo", + "PanelInfo", + "MediaInfo", + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Discovery Engine + API needs to know about how end users interact with your + website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + Generic values: + + - ``search``: Search for Documents. + - ``view-item``: Detailed page view of a Document. + - ``view-item-list``: View of a panel or ordered list of + Documents. + - ``view-home-page``: View of the home page. + - ``view-category-page``: View of a category page, e.g. Home + > Men > Jeans + - ``add-feedback``: Add a user feedback. + + Retail-related values: + + - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail + online shopping + - ``purchase``: Purchase an item(s) + + Media-related values: + + - ``media-play``: Start/resume watching a video, playing a + song, etc. + - ``media-complete``: Finished or stopped midway through a + video, song, etc. + user_pseudo_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Do not set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + engine (str): + The [Engine][google.cloud.discoveryengine.v1beta.Engine] + resource name, in the form of + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + Optional. Only required for + [Engine][google.cloud.discoveryengine.v1beta.Engine] + produced user events. For example, user events from blended + search. + data_store (str): + The + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + resource full name, of the form + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + Optional. Only required for user events whose data store + can't by determined by + [UserEvent.engine][google.cloud.discoveryengine.v1beta.UserEvent.engine] + or + [UserEvent.documents][google.cloud.discoveryengine.v1beta.UserEvent.documents]. + If data store is set in the parent of write/import/collect + user event requests, this field can be omitted. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): + Information about the end user. + direct_user_request (bool): + Should set to true if the request is made directly from the + end user, in which case the + [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1beta.UserInfo.user_agent] + can be populated from the HTTP request. + + This flag should be set only if the API request is made + directly from the end user such as a mobile app (and not if + a gateway or a server is processing and pushing the user + events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent]. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the session_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + as prefix. + page_info (google.cloud.discoveryengine_v1beta.types.PageInfo): + Page metadata such as categories and other critical + information for certain event types such as + ``view-category-page``. + attribution_token (str): + Token to attribute an API response to user action(s) to + trigger the event. + + Highly recommended for user events that are the result of + [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]. + This field enables accurate attribution of recommendation + model performance. + + The value must be one of: + + - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] + for events that are the result of + [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]. + - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1beta.SearchResponse.attribution_token] + for events that are the result of + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search]. + + This token enables us to accurately attribute page view or + conversion completion back to the event and the particular + predict response containing this clicked/purchased product. + If user clicks on product K in the recommendation results, + pass + [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] + to this field. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. + + One example is for ``search`` events, the associated + [SearchRequest][google.cloud.discoveryengine.v1beta.SearchRequest] + may contain a filter expression in + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter] + conforming to https://google.aip.dev/160#filtering. + + Similarly, for ``view-item-list`` events that are generated + from a + [RecommendRequest][google.cloud.discoveryengine.v1beta.RecommendRequest], + this field may be populated directly from + [RecommendRequest.filter][google.cloud.discoveryengine.v1beta.RecommendRequest.filter] + conforming to https://google.aip.dev/160#filtering. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.DocumentInfo]): + List of + [Document][google.cloud.discoveryengine.v1beta.Document]s + associated with this user event. + + This field is optional except for the following event types: + + - ``view-item`` + - ``add-to-cart`` + - ``purchase`` + - ``media-play`` + - ``media-complete`` + + In a ``search`` event, this field represents the documents + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [UserEvent.documents][google.cloud.discoveryengine.v1beta.UserEvent.documents] + is desired. + panel (google.cloud.discoveryengine_v1beta.types.PanelInfo): + Panel metadata associated with this user + event. + search_info (google.cloud.discoveryengine_v1beta.types.SearchInfo): + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + details related to the event. + + This field should be set for ``search`` event. + completion_info (google.cloud.discoveryengine_v1beta.types.CompletionInfo): + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + transaction_info (google.cloud.discoveryengine_v1beta.types.TransactionInfo): + The transaction metadata (if any) associated + with this user event. + tag_ids (MutableSequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups. + promotion_ids (MutableSequence[str]): + The promotion IDs if this is an event + associated with promotions. Currently, this + field is restricted to at most one ID. + attributes (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. These attributes must NOT contain data that needs to + be parsed or processed further, e.g. JSON or other + encodings. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Discovery Engine API use + those custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + ``INVALID_ARGUMENT`` error is returned: + + - The key must be a UTF-8 encoded string with a length limit + of 5,000 characters. + - For text attributes, at most 400 values are allowed. Empty + values are not allowed. Each value must be a UTF-8 encoded + string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is ``traffic_channel``, which is how a user + arrives at the site. Users can arrive at the site by coming + to the site directly, coming through Google search, or in + other ways. + media_info (google.cloud.discoveryengine_v1beta.types.MediaInfo): + Media-specific info. + panels (MutableSequence[google.cloud.discoveryengine_v1beta.types.PanelInfo]): + Optional. List of panels associated with this + event. Used for page-level impression data. + """ + + event_type: str = proto.Field( + proto.STRING, + number=1, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=2, + ) + engine: str = proto.Field( + proto.STRING, + number=19, + ) + data_store: str = proto.Field( + proto.STRING, + number=20, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=4, + message=common.UserInfo, + ) + direct_user_request: bool = proto.Field( + proto.BOOL, + number=5, + ) + session_id: str = proto.Field( + proto.STRING, + number=6, + ) + page_info: "PageInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="PageInfo", + ) + attribution_token: str = proto.Field( + proto.STRING, + number=8, + ) + filter: str = proto.Field( + proto.STRING, + number=9, + ) + documents: MutableSequence["DocumentInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="DocumentInfo", + ) + panel: "PanelInfo" = proto.Field( + proto.MESSAGE, + number=11, + message="PanelInfo", + ) + search_info: "SearchInfo" = proto.Field( + proto.MESSAGE, + number=12, + message="SearchInfo", + ) + completion_info: "CompletionInfo" = proto.Field( + proto.MESSAGE, + number=13, + message="CompletionInfo", + ) + transaction_info: "TransactionInfo" = proto.Field( + proto.MESSAGE, + number=14, + message="TransactionInfo", + ) + tag_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=16, + ) + attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=17, + message=common.CustomAttribute, + ) + media_info: "MediaInfo" = proto.Field( + proto.MESSAGE, + number=18, + message="MediaInfo", + ) + panels: MutableSequence["PanelInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message="PanelInfo", + ) + + +class PageInfo(proto.Message): + r"""Detailed page information. + + Attributes: + pageview_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageview_id`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + page_category (str): + The most specific category associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: + ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. + + Required for ``view-category-page`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. However, some + browser privacy restrictions may cause this + field to be empty. + """ + + pageview_id: str = proto.Field( + proto.STRING, + number=1, + ) + page_category: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + referrer_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchInfo(proto.Message): + r"""Detailed search information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.discoveryengine.v1beta.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + At least one of + [search_query][google.cloud.discoveryengine.v1beta.SearchInfo.search_query] + or + [PageInfo.page_category][google.cloud.discoveryengine.v1beta.PageInfo.page_category] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + order_by (str): + The order in which products are returned, if applicable. + + See + [SearchRequest.order_by][google.cloud.discoveryengine.v1beta.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.discoveryengine.v1beta.SearchRequest.offset] + for definition. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + This field is a member of `oneof`_ ``_offset``. + """ + + search_query: str = proto.Field( + proto.STRING, + number=1, + ) + order_by: str = proto.Field( + proto.STRING, + number=2, + ) + offset: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + + +class CompletionInfo(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + selected_suggestion (str): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1beta.CompleteQueryResponse.QuerySuggestion.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1beta.CompleteQueryResponse.QuerySuggestion.suggestion] + position, starting from 0. + """ + + selected_suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + selected_position: int = proto.Field( + proto.INT32, + number=2, + ) + + +class TransactionInfo(proto.Message): + r"""A transaction represents the entire purchase transaction. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + Required. Total non-zero value associated + with the transaction. This value may include + shipping, tax, or other adjustments to the total + value that you want to include. + + This field is a member of `oneof`_ ``_value``. + currency (str): + Required. Currency code. Use three-character + ISO-4217 code. + transaction_id (str): + The transaction ID with a length limit of 128 + characters. + tax (float): + All the taxes associated with the + transaction. + + This field is a member of `oneof`_ ``_tax``. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1beta.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1beta.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_cost``. + discount_value (float): + The total discount(s) value applied to this transaction. + This figure should be excluded from + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + + For example, if a user paid + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + amount, then nominal (pre-discount) value of the transaction + is the sum of + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + and + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1beta.TransactionInfo.discount_value] + + This means that profit is calculated the same way, + regardless of the discount value, and that + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1beta.TransactionInfo.discount_value] + can be larger than + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value]: + + - Profit = + [value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1beta.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1beta.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_discount_value``. + """ + + value: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + currency: str = proto.Field( + proto.STRING, + number=2, + ) + transaction_id: str = proto.Field( + proto.STRING, + number=3, + ) + tax: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + cost: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + discount_value: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + + +class DocumentInfo(proto.Message): + r"""Detailed document information associated with a user event. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + The [Document][google.cloud.discoveryengine.v1beta.Document] + resource ID. + + This field is a member of `oneof`_ ``document_descriptor``. + name (str): + The [Document][google.cloud.discoveryengine.v1beta.Document] + resource full name, of the form: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` + + This field is a member of `oneof`_ ``document_descriptor``. + uri (str): + The [Document][google.cloud.discoveryengine.v1beta.Document] + URI - only allowed for website data stores. + + This field is a member of `oneof`_ ``document_descriptor``. + quantity (int): + Quantity of the Document associated with the user event. + Defaults to 1. + + For example, this field is 2 if two quantities of the same + Document are involved in a ``add-to-cart`` event. + + Required for events of the following event types: + + - ``add-to-cart`` + - ``purchase`` + + This field is a member of `oneof`_ ``_quantity``. + promotion_ids (MutableSequence[str]): + The promotion IDs associated with this + Document. Currently, this field is restricted to + at most one ID. + joined (bool): + Output only. Whether the referenced Document + can be found in the data store. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + oneof="document_descriptor", + ) + name: str = proto.Field( + proto.STRING, + number=2, + oneof="document_descriptor", + ) + uri: str = proto.Field( + proto.STRING, + number=6, + oneof="document_descriptor", + ) + quantity: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + joined: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class PanelInfo(proto.Message): + r"""Detailed panel information associated with a user event. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + panel_id (str): + Required. The panel ID. + display_name (str): + The display name of the panel. + panel_position (int): + The ordered position of the panel, if shown to the user with + other panels. If set, then + [total_panels][google.cloud.discoveryengine.v1beta.PanelInfo.total_panels] + must also be set. + + This field is a member of `oneof`_ ``_panel_position``. + total_panels (int): + The total number of panels, including this one, shown to the + user. Must be set if + [panel_position][google.cloud.discoveryengine.v1beta.PanelInfo.panel_position] + is set. + + This field is a member of `oneof`_ ``_total_panels``. + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.DocumentInfo]): + Optional. The document IDs associated with + this panel. + """ + + panel_id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + panel_position: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + total_panels: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + documents: MutableSequence["DocumentInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="DocumentInfo", + ) + + +class MediaInfo(proto.Message): + r"""Media-specific user event information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + media_progress_duration (google.protobuf.duration_pb2.Duration): + The media progress time in seconds, if applicable. For + example, if the end user has finished 90 seconds of a + playback video, then + [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] + should be set to 90. + media_progress_percentage (float): + Media progress should be computed using only the + [media_progress_duration][google.cloud.discoveryengine.v1beta.MediaInfo.media_progress_duration] + relative to the media total length. + + This value must be between ``[0, 1.0]`` inclusive. + + If this is not a playback or the progress cannot be computed + (e.g. ongoing livestream), this field should be unset. + + This field is a member of `oneof`_ ``_media_progress_percentage``. + """ + + media_progress_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + media_progress_percentage: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/user_event_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/user_event_service.py new file mode 100644 index 0000000000000000000000000000000000000000..8be711e32aeb06aef7d442136eb129e3b14a50e6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/discoveryengine_v1beta/types/user_event_service.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import user_event as gcd_user_event + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "WriteUserEventRequest", + "CollectUserEventRequest", + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource name. If the write user event + action is applied in + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + level, the format is: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + If the write user event action is applied in [Location][] + level, for example, the event with + [Document][google.cloud.discoveryengine.v1beta.Document] + across multiple + [DataStore][google.cloud.discoveryengine.v1beta.DataStore], + the format is: ``projects/{project}/locations/{location}``. + user_event (google.cloud.discoveryengine_v1beta.types.UserEvent): + Required. User event to write. + + This field is a member of `oneof`_ ``_user_event``. + write_async (bool): + If set to true, the user event is written + asynchronously after validation, and the API + responds without waiting for the write. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=gcd_user_event.UserEvent, + ) + write_async: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for third-party requests. + + This field is a member of `oneof`_ ``_uri``. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + + This field is a member of `oneof`_ ``_ets``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + ets: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/environment_vars/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/environment_vars/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d84afca3562801bba251d1c19a24c757842a3a54 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/environment_vars/__init__.py @@ -0,0 +1,38 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Comprehensive list of environment variables used in google-cloud. + +These enable many types of implicit behavior in both production +and tests. +""" + +GCD_DATASET = "DATASTORE_DATASET" +"""Environment variable defining default dataset ID under GCD.""" + +GCD_HOST = "DATASTORE_EMULATOR_HOST" +"""Environment variable defining host for GCD dataset server.""" + +PUBSUB_EMULATOR = "PUBSUB_EMULATOR_HOST" +"""Environment variable defining host for Pub/Sub emulator.""" + +BIGTABLE_EMULATOR = "BIGTABLE_EMULATOR_HOST" +"""Environment variable defining host for Bigtable emulator.""" + +DISABLE_GRPC = "GOOGLE_CLOUD_DISABLE_GRPC" +"""Environment variable acting as flag to disable gRPC. + +To be used for APIs where both an HTTP and gRPC implementation +exist. +""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/environment_vars/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/environment_vars/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dfc5374a1bac545c8bc07365e9d5579010a7736c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/environment_vars/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# This package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36ee6d14fcabc3f2c695bf82092db88056330aba --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/__init__.py @@ -0,0 +1,59 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: disable=invalid-name +# pylint recognizies all of these aliases as constants and thinks they have +# invalid names. + +"""Custom exceptions for :mod:`google.cloud` package.""" + +# Avoid the grpc and google.cloud.grpc collision. +from __future__ import absolute_import + +from google.api_core import exceptions + +try: + from grpc._channel import _Rendezvous +except ImportError: # pragma: NO COVER + _Rendezvous = None + +GrpcRendezvous = _Rendezvous +"""Exception class raised by gRPC stable.""" + +# Aliases to moved classes. +GoogleCloudError = exceptions.GoogleAPICallError +Redirection = exceptions.Redirection +MovedPermanently = exceptions.MovedPermanently +NotModified = exceptions.NotModified +TemporaryRedirect = exceptions.TemporaryRedirect +ResumeIncomplete = exceptions.ResumeIncomplete +ClientError = exceptions.ClientError +BadRequest = exceptions.BadRequest +Unauthorized = exceptions.Unauthorized +Forbidden = exceptions.Forbidden +NotFound = exceptions.NotFound +MethodNotAllowed = exceptions.MethodNotAllowed +Conflict = exceptions.Conflict +LengthRequired = exceptions.LengthRequired +PreconditionFailed = exceptions.PreconditionFailed +RequestRangeNotSatisfiable = exceptions.RequestRangeNotSatisfiable +TooManyRequests = exceptions.TooManyRequests +ServerError = exceptions.ServerError +InternalServerError = exceptions.InternalServerError +MethodNotImplemented = exceptions.MethodNotImplemented +BadGateway = exceptions.BadGateway +ServiceUnavailable = exceptions.ServiceUnavailable +GatewayTimeout = exceptions.GatewayTimeout +from_http_status = exceptions.from_http_status +from_http_response = exceptions.from_http_response diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d9b47cbe4967eec35282a0a287190904eb4cc34 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dfc5374a1bac545c8bc07365e9d5579010a7736c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/exceptions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# This package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations.proto new file mode 100644 index 0000000000000000000000000000000000000000..69f44ddac856c6b41cd81f89b453079150b24bb3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations.proto @@ -0,0 +1,150 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file contains custom annotations that are used by GAPIC generators to +// handle Long Running Operation methods (LRO) that are NOT compliant with +// https://google.aip.dev/151. These annotations are public for technical +// reasons only. Please DO NOT USE them in your protos. +syntax = "proto3"; + +package google.cloud; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/cloud/extendedops;extendedops"; +option java_multiple_files = true; +option java_outer_classname = "ExtendedOperationsProto"; +option java_package = "com.google.cloud"; +option objc_class_prefix = "GAPI"; + +// FieldOptions to match corresponding fields in the initial request, +// polling request and operation response messages. +// +// Example: +// +// In an API-specific operation message: +// +// message MyOperation { +// string http_error_message = 1 [(operation_field) = ERROR_MESSAGE]; +// int32 http_error_status_code = 2 [(operation_field) = ERROR_CODE]; +// string id = 3 [(operation_field) = NAME]; +// Status status = 4 [(operation_field) = STATUS]; +// } +// +// In a polling request message (the one which is used to poll for an LRO +// status): +// +// message MyPollingRequest { +// string operation = 1 [(operation_response_field) = "id"]; +// string project = 2; +// string region = 3; +// } +// +// In an initial request message (the one which starts an LRO): +// +// message MyInitialRequest { +// string my_project = 2 [(operation_request_field) = "project"]; +// string my_region = 3 [(operation_request_field) = "region"]; +// } +// +extend google.protobuf.FieldOptions { + // A field annotation that maps fields in an API-specific Operation object to + // their standard counterparts in google.longrunning.Operation. See + // OperationResponseMapping enum definition. + OperationResponseMapping operation_field = 1149; + + // A field annotation that maps fields in the initial request message + // (the one which started the LRO) to their counterparts in the polling + // request message. For non-standard LRO, the polling response may be missing + // some of the information needed to make a subsequent polling request. The + // missing information (for example, project or region ID) is contained in the + // fields of the initial request message that this annotation must be applied + // to. The string value of the annotation corresponds to the name of the + // counterpart field in the polling request message that the annotated field's + // value will be copied to. + string operation_request_field = 1150; + + // A field annotation that maps fields in the polling request message to their + // counterparts in the initial and/or polling response message. The initial + // and the polling methods return an API-specific Operation object. Some of + // the fields from that response object must be reused in the subsequent + // request (like operation name/ID) to fully identify the polled operation. + // This annotation must be applied to the fields in the polling request + // message, the string value of the annotation must correspond to the name of + // the counterpart field in the Operation response object whose value will be + // copied to the annotated field. + string operation_response_field = 1151; +} + +// MethodOptions to identify the actual service and method used for operation +// status polling. +// +// Example: +// +// In a method, which starts an LRO: +// +// service MyService { +// rpc Foo(MyInitialRequest) returns (MyOperation) { +// option (operation_service) = "MyPollingService"; +// } +// } +// +// In a polling method: +// +// service MyPollingService { +// rpc Get(MyPollingRequest) returns (MyOperation) { +// option (operation_polling_method) = true; +// } +// } +extend google.protobuf.MethodOptions { + // A method annotation that maps an LRO method (the one which starts an LRO) + // to the service, which will be used to poll for the operation status. The + // annotation must be applied to the method which starts an LRO, the string + // value of the annotation must correspond to the name of the service used to + // poll for the operation status. + string operation_service = 1249; + + // A method annotation that marks methods that can be used for polling + // operation status (e.g. the MyPollingService.Get(MyPollingRequest) method). + bool operation_polling_method = 1250; +} + +// An enum to be used to mark the essential (for polling) fields in an +// API-specific Operation object. A custom Operation object may contain many +// different fields, but only few of them are essential to conduct a successful +// polling process. +enum OperationResponseMapping { + // Do not use. + UNDEFINED = 0; + + // A field in an API-specific (custom) Operation object which carries the same + // meaning as google.longrunning.Operation.name. + NAME = 1; + + // A field in an API-specific (custom) Operation object which carries the same + // meaning as google.longrunning.Operation.done. If the annotated field is of + // an enum type, `annotated_field_name == EnumType.DONE` semantics should be + // equivalent to `Operation.done == true`. If the annotated field is of type + // boolean, then it should follow the same semantics as Operation.done. + // Otherwise, a non-empty value should be treated as `Operation.done == true`. + STATUS = 2; + + // A field in an API-specific (custom) Operation object which carries the same + // meaning as google.longrunning.Operation.error.code. + ERROR_CODE = 3; + + // A field in an API-specific (custom) Operation object which carries the same + // meaning as google.longrunning.Operation.error.message. + ERROR_MESSAGE = 4; +} \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..679ce3e3150bfab52c7041f19fcc4d86221cb0b0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/extended_operations.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n&google/cloud/extended_operations.proto\x12\x0cgoogle.cloud\x1a google/protobuf/descriptor.proto*b\n\x18OperationResponseMapping\x12\r\n\tUNDEFINED\x10\x00\x12\x08\n\x04NAME\x10\x01\x12\n\n\x06STATUS\x10\x02\x12\x0e\n\nERROR_CODE\x10\x03\x12\x11\n\rERROR_MESSAGE\x10\x04:_\n\x0foperation_field\x12\x1d.google.protobuf.FieldOptions\x18\xfd\x08 \x01(\x0e\x32&.google.cloud.OperationResponseMapping:?\n\x17operation_request_field\x12\x1d.google.protobuf.FieldOptions\x18\xfe\x08 \x01(\t:@\n\x18operation_response_field\x12\x1d.google.protobuf.FieldOptions\x18\xff\x08 \x01(\t::\n\x11operation_service\x12\x1e.google.protobuf.MethodOptions\x18\xe1\t \x01(\t:A\n\x18operation_polling_method\x12\x1e.google.protobuf.MethodOptions\x18\xe2\t \x01(\x08\x42y\n\x10\x63om.google.cloudB\x17\x45xtendedOperationsProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/extendedops;extendedops\xa2\x02\x04GAPIb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.cloud.extended_operations_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\020com.google.cloudB\027ExtendedOperationsProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/extendedops;extendedops\242\002\004GAPI" + _globals["_OPERATIONRESPONSEMAPPING"]._serialized_start = 90 + _globals["_OPERATIONRESPONSEMAPPING"]._serialized_end = 188 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8f29d450773d938dbbba678a4822d04fa24aee52 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/extended_operations_pb2.pyi @@ -0,0 +1,45 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pb2 as _descriptor_pb2 +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class OperationResponseMapping(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + UNDEFINED: _ClassVar[OperationResponseMapping] + NAME: _ClassVar[OperationResponseMapping] + STATUS: _ClassVar[OperationResponseMapping] + ERROR_CODE: _ClassVar[OperationResponseMapping] + ERROR_MESSAGE: _ClassVar[OperationResponseMapping] + +UNDEFINED: OperationResponseMapping +NAME: OperationResponseMapping +STATUS: OperationResponseMapping +ERROR_CODE: OperationResponseMapping +ERROR_MESSAGE: OperationResponseMapping +OPERATION_FIELD_FIELD_NUMBER: _ClassVar[int] +operation_field: _descriptor.FieldDescriptor +OPERATION_REQUEST_FIELD_FIELD_NUMBER: _ClassVar[int] +operation_request_field: _descriptor.FieldDescriptor +OPERATION_RESPONSE_FIELD_FIELD_NUMBER: _ClassVar[int] +operation_response_field: _descriptor.FieldDescriptor +OPERATION_SERVICE_FIELD_NUMBER: _ClassVar[int] +operation_service: _descriptor.FieldDescriptor +OPERATION_POLLING_METHOD_FIELD_NUMBER: _ClassVar[int] +operation_polling_method: _descriptor.FieldDescriptor diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a435baa9540875c947ec3546b0b31653e1092f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/__init__.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.iam import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.iam_v2.services.policies.async_client import PoliciesAsyncClient +from google.cloud.iam_v2.services.policies.client import PoliciesClient +from google.cloud.iam_v2.types.deny import DenyRule +from google.cloud.iam_v2.types.policy import ( + CreatePolicyRequest, + DeletePolicyRequest, + GetPolicyRequest, + ListPoliciesRequest, + ListPoliciesResponse, + Policy, + PolicyOperationMetadata, + PolicyRule, + UpdatePolicyRequest, +) + +__all__ = ( + "PoliciesClient", + "PoliciesAsyncClient", + "DenyRule", + "CreatePolicyRequest", + "DeletePolicyRequest", + "GetPolicyRequest", + "ListPoliciesRequest", + "ListPoliciesResponse", + "Policy", + "PolicyOperationMetadata", + "PolicyRule", + "UpdatePolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..adb07bfbc0c7235ee09803595f484824b000f9bd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/__init__.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.iam_admin import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.iam_admin_v1.services.iam.async_client import IAMAsyncClient +from google.cloud.iam_admin_v1.services.iam.client import IAMClient +from google.cloud.iam_admin_v1.types.audit_data import AuditData +from google.cloud.iam_admin_v1.types.iam import ( + CreateRoleRequest, + CreateServiceAccountKeyRequest, + CreateServiceAccountRequest, + DeleteRoleRequest, + DeleteServiceAccountKeyRequest, + DeleteServiceAccountRequest, + DisableServiceAccountKeyRequest, + DisableServiceAccountRequest, + EnableServiceAccountKeyRequest, + EnableServiceAccountRequest, + GetRoleRequest, + GetServiceAccountKeyRequest, + GetServiceAccountRequest, + LintPolicyRequest, + LintPolicyResponse, + LintResult, + ListRolesRequest, + ListRolesResponse, + ListServiceAccountKeysRequest, + ListServiceAccountKeysResponse, + ListServiceAccountsRequest, + ListServiceAccountsResponse, + PatchServiceAccountRequest, + Permission, + QueryAuditableServicesRequest, + QueryAuditableServicesResponse, + QueryGrantableRolesRequest, + QueryGrantableRolesResponse, + QueryTestablePermissionsRequest, + QueryTestablePermissionsResponse, + Role, + RoleView, + ServiceAccount, + ServiceAccountKey, + ServiceAccountKeyAlgorithm, + ServiceAccountKeyOrigin, + ServiceAccountPrivateKeyType, + ServiceAccountPublicKeyType, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, + UndeleteRoleRequest, + UndeleteServiceAccountRequest, + UndeleteServiceAccountResponse, + UpdateRoleRequest, + UploadServiceAccountKeyRequest, +) + +__all__ = ( + "IAMClient", + "IAMAsyncClient", + "AuditData", + "CreateRoleRequest", + "CreateServiceAccountKeyRequest", + "CreateServiceAccountRequest", + "DeleteRoleRequest", + "DeleteServiceAccountKeyRequest", + "DeleteServiceAccountRequest", + "DisableServiceAccountKeyRequest", + "DisableServiceAccountRequest", + "EnableServiceAccountKeyRequest", + "EnableServiceAccountRequest", + "GetRoleRequest", + "GetServiceAccountKeyRequest", + "GetServiceAccountRequest", + "LintPolicyRequest", + "LintPolicyResponse", + "LintResult", + "ListRolesRequest", + "ListRolesResponse", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "PatchServiceAccountRequest", + "Permission", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "Role", + "ServiceAccount", + "ServiceAccountKey", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "UndeleteRoleRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "UpdateRoleRequest", + "UploadServiceAccountKeyRequest", + "RoleView", + "ServiceAccountKeyAlgorithm", + "ServiceAccountKeyOrigin", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..894b005dd6254d3d9f0d1c35d442bcd0a9f76f3d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/__init__.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.iam_admin_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.iam import IAMAsyncClient, IAMClient +from .types.audit_data import AuditData +from .types.iam import ( + CreateRoleRequest, + CreateServiceAccountKeyRequest, + CreateServiceAccountRequest, + DeleteRoleRequest, + DeleteServiceAccountKeyRequest, + DeleteServiceAccountRequest, + DisableServiceAccountKeyRequest, + DisableServiceAccountRequest, + EnableServiceAccountKeyRequest, + EnableServiceAccountRequest, + GetRoleRequest, + GetServiceAccountKeyRequest, + GetServiceAccountRequest, + LintPolicyRequest, + LintPolicyResponse, + LintResult, + ListRolesRequest, + ListRolesResponse, + ListServiceAccountKeysRequest, + ListServiceAccountKeysResponse, + ListServiceAccountsRequest, + ListServiceAccountsResponse, + PatchServiceAccountRequest, + Permission, + QueryAuditableServicesRequest, + QueryAuditableServicesResponse, + QueryGrantableRolesRequest, + QueryGrantableRolesResponse, + QueryTestablePermissionsRequest, + QueryTestablePermissionsResponse, + Role, + RoleView, + ServiceAccount, + ServiceAccountKey, + ServiceAccountKeyAlgorithm, + ServiceAccountKeyOrigin, + ServiceAccountPrivateKeyType, + ServiceAccountPublicKeyType, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, + UndeleteRoleRequest, + UndeleteServiceAccountRequest, + UndeleteServiceAccountResponse, + UpdateRoleRequest, + UploadServiceAccountKeyRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.iam_admin_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.iam_admin_v1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.iam_admin_v1" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "IAMAsyncClient", + "AuditData", + "CreateRoleRequest", + "CreateServiceAccountKeyRequest", + "CreateServiceAccountRequest", + "DeleteRoleRequest", + "DeleteServiceAccountKeyRequest", + "DeleteServiceAccountRequest", + "DisableServiceAccountKeyRequest", + "DisableServiceAccountRequest", + "EnableServiceAccountKeyRequest", + "EnableServiceAccountRequest", + "GetRoleRequest", + "GetServiceAccountKeyRequest", + "GetServiceAccountRequest", + "IAMClient", + "LintPolicyRequest", + "LintPolicyResponse", + "LintResult", + "ListRolesRequest", + "ListRolesResponse", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "PatchServiceAccountRequest", + "Permission", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "Role", + "RoleView", + "ServiceAccount", + "ServiceAccountKey", + "ServiceAccountKeyAlgorithm", + "ServiceAccountKeyOrigin", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "UndeleteRoleRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "UpdateRoleRequest", + "UploadServiceAccountKeyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7de812d7d0c56192e6f681556370d21e5bfeb934 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/gapic_metadata.json @@ -0,0 +1,333 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_admin_v1", + "protoPackage": "google.iam.admin.v1", + "schema": "1.0", + "services": { + "IAM": { + "clients": { + "grpc": { + "libraryClient": "IAMClient", + "rpcs": { + "CreateRole": { + "methods": [ + "create_role" + ] + }, + "CreateServiceAccount": { + "methods": [ + "create_service_account" + ] + }, + "CreateServiceAccountKey": { + "methods": [ + "create_service_account_key" + ] + }, + "DeleteRole": { + "methods": [ + "delete_role" + ] + }, + "DeleteServiceAccount": { + "methods": [ + "delete_service_account" + ] + }, + "DeleteServiceAccountKey": { + "methods": [ + "delete_service_account_key" + ] + }, + "DisableServiceAccount": { + "methods": [ + "disable_service_account" + ] + }, + "DisableServiceAccountKey": { + "methods": [ + "disable_service_account_key" + ] + }, + "EnableServiceAccount": { + "methods": [ + "enable_service_account" + ] + }, + "EnableServiceAccountKey": { + "methods": [ + "enable_service_account_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetRole": { + "methods": [ + "get_role" + ] + }, + "GetServiceAccount": { + "methods": [ + "get_service_account" + ] + }, + "GetServiceAccountKey": { + "methods": [ + "get_service_account_key" + ] + }, + "LintPolicy": { + "methods": [ + "lint_policy" + ] + }, + "ListRoles": { + "methods": [ + "list_roles" + ] + }, + "ListServiceAccountKeys": { + "methods": [ + "list_service_account_keys" + ] + }, + "ListServiceAccounts": { + "methods": [ + "list_service_accounts" + ] + }, + "PatchServiceAccount": { + "methods": [ + "patch_service_account" + ] + }, + "QueryAuditableServices": { + "methods": [ + "query_auditable_services" + ] + }, + "QueryGrantableRoles": { + "methods": [ + "query_grantable_roles" + ] + }, + "QueryTestablePermissions": { + "methods": [ + "query_testable_permissions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteRole": { + "methods": [ + "undelete_role" + ] + }, + "UndeleteServiceAccount": { + "methods": [ + "undelete_service_account" + ] + }, + "UpdateRole": { + "methods": [ + "update_role" + ] + }, + "UpdateServiceAccount": { + "methods": [ + "update_service_account" + ] + }, + "UploadServiceAccountKey": { + "methods": [ + "upload_service_account_key" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IAMAsyncClient", + "rpcs": { + "CreateRole": { + "methods": [ + "create_role" + ] + }, + "CreateServiceAccount": { + "methods": [ + "create_service_account" + ] + }, + "CreateServiceAccountKey": { + "methods": [ + "create_service_account_key" + ] + }, + "DeleteRole": { + "methods": [ + "delete_role" + ] + }, + "DeleteServiceAccount": { + "methods": [ + "delete_service_account" + ] + }, + "DeleteServiceAccountKey": { + "methods": [ + "delete_service_account_key" + ] + }, + "DisableServiceAccount": { + "methods": [ + "disable_service_account" + ] + }, + "DisableServiceAccountKey": { + "methods": [ + "disable_service_account_key" + ] + }, + "EnableServiceAccount": { + "methods": [ + "enable_service_account" + ] + }, + "EnableServiceAccountKey": { + "methods": [ + "enable_service_account_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetRole": { + "methods": [ + "get_role" + ] + }, + "GetServiceAccount": { + "methods": [ + "get_service_account" + ] + }, + "GetServiceAccountKey": { + "methods": [ + "get_service_account_key" + ] + }, + "LintPolicy": { + "methods": [ + "lint_policy" + ] + }, + "ListRoles": { + "methods": [ + "list_roles" + ] + }, + "ListServiceAccountKeys": { + "methods": [ + "list_service_account_keys" + ] + }, + "ListServiceAccounts": { + "methods": [ + "list_service_accounts" + ] + }, + "PatchServiceAccount": { + "methods": [ + "patch_service_account" + ] + }, + "QueryAuditableServices": { + "methods": [ + "query_auditable_services" + ] + }, + "QueryGrantableRoles": { + "methods": [ + "query_grantable_roles" + ] + }, + "QueryTestablePermissions": { + "methods": [ + "query_testable_permissions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteRole": { + "methods": [ + "undelete_role" + ] + }, + "UndeleteServiceAccount": { + "methods": [ + "undelete_service_account" + ] + }, + "UpdateRole": { + "methods": [ + "update_role" + ] + }, + "UpdateServiceAccount": { + "methods": [ + "update_service_account" + ] + }, + "UploadServiceAccountKey": { + "methods": [ + "upload_service_account_key" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e66727104187446872826e1f95a0f79a44ce55d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import IAMAsyncClient +from .client import IAMClient + +__all__ = ( + "IAMClient", + "IAMAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e5debd1132bd77fb5dd3273c2b416f31a223157a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/async_client.py @@ -0,0 +1,3922 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +import warnings +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_admin_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.iam_admin_v1.services.iam import pagers +from google.cloud.iam_admin_v1.types import iam + +from .client import IAMClient +from .transports.base import DEFAULT_CLIENT_INFO, IAMTransport +from .transports.grpc_asyncio import IAMGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class IAMAsyncClient: + """Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + """ + + _client: IAMClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = IAMClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IAMClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = IAMClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = IAMClient._DEFAULT_UNIVERSE + + key_path = staticmethod(IAMClient.key_path) + parse_key_path = staticmethod(IAMClient.parse_key_path) + service_account_path = staticmethod(IAMClient.service_account_path) + parse_service_account_path = staticmethod(IAMClient.parse_service_account_path) + common_billing_account_path = staticmethod(IAMClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod( + IAMClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(IAMClient.common_folder_path) + parse_common_folder_path = staticmethod(IAMClient.parse_common_folder_path) + common_organization_path = staticmethod(IAMClient.common_organization_path) + parse_common_organization_path = staticmethod( + IAMClient.parse_common_organization_path + ) + common_project_path = staticmethod(IAMClient.common_project_path) + parse_common_project_path = staticmethod(IAMClient.parse_common_project_path) + common_location_path = staticmethod(IAMClient.common_location_path) + parse_common_location_path = staticmethod(IAMClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMAsyncClient: The constructed client. + """ + sa_info_func = ( + IAMClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(IAMAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMAsyncClient: The constructed client. + """ + sa_file_func = ( + IAMClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(IAMAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return IAMClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> IAMTransport: + """Returns the transport used by the client instance. + + Returns: + IAMTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = IAMClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMTransport, Callable[..., IAMTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the iam async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,IAMTransport,Callable[..., IAMTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the IAMTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = IAMClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam.admin_v1.IAMAsyncClient`.", + extra={ + "serviceName": "google.iam.admin.v1.IAM", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.admin.v1.IAM", + "credentialsType": None, + }, + ) + + async def list_service_accounts( + self, + request: Optional[Union[iam.ListServiceAccountsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListServiceAccountsAsyncPager: + r"""Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_list_service_accounts(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_service_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ListServiceAccountsRequest, dict]]): + The request object. The service account list request. + name (:class:`str`): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListServiceAccountsAsyncPager: + The service account list response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ListServiceAccountsRequest): + request = iam.ListServiceAccountsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_service_accounts + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServiceAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service_account( + self, + request: Optional[Union[iam.GetServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_get_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.GetServiceAccountRequest, dict]]): + The request object. The service account get request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.GetServiceAccountRequest): + request = iam.GetServiceAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service_account( + self, + request: Optional[Union[iam.CreateServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + account_id: Optional[str] = None, + service_account: Optional[iam.ServiceAccount] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_create_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Make the request + response = await client.create_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.CreateServiceAccountRequest, dict]]): + The request object. The service account create request. + name (:class:`str`): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + account_id (:class:`str`): + Required. The account id that is used to generate the + service account email address and a stable unique id. It + is unique within a project, must be 6-30 characters + long, and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])`` to comply with RFC1035. + + This corresponds to the ``account_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_account (:class:`google.cloud.iam_admin_v1.types.ServiceAccount`): + The [ServiceAccount][google.iam.admin.v1.ServiceAccount] + resource to create. Currently, only the following values + are user assignable: ``display_name`` and + ``description``. + + This corresponds to the ``service_account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, account_id, service_account] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.CreateServiceAccountRequest): + request = iam.CreateServiceAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if account_id is not None: + request.account_id = account_id + if service_account is not None: + request.service_account = service_account + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_service_account( + self, + request: Optional[Union[iam.ServiceAccount, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""**Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_update_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ServiceAccount( + ) + + # Make the request + response = await client.update_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ServiceAccount, dict]]): + The request object. An IAM service account. + + A service account is an account for an application or a + virtual machine (VM) instance, not a person. You can use + a service account to call Google APIs. To learn more, + read the `overview of service + accounts `__. + + When you create a service account, you specify the + project ID that owns the service account, as well as a + name that must be unique within the project. IAM uses + these values to create an email address that identifies + the service account. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ServiceAccount): + request = iam.ServiceAccount(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def patch_service_account( + self, + request: Optional[Union[iam.PatchServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_patch_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.PatchServiceAccountRequest( + ) + + # Make the request + response = await client.patch_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.PatchServiceAccountRequest, dict]]): + The request object. The service account patch request. + + You can patch only the ``display_name`` and + ``description`` fields. You must use the ``update_mask`` + field to specify which of these fields you want to + patch. + + Only the fields specified in the request are guaranteed + to be returned in the response. Other fields may be + empty in the response. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.PatchServiceAccountRequest): + request = iam.PatchServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.patch_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("service_account.name", request.service_account.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_service_account( + self, + request: Optional[Union[iam.DeleteServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_delete_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_service_account(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountRequest, dict]]): + The request object. The service account delete request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DeleteServiceAccountRequest): + request = iam.DeleteServiceAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def undelete_service_account( + self, + request: Optional[Union[iam.UndeleteServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.UndeleteServiceAccountResponse: + r"""Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_undelete_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteServiceAccountRequest( + ) + + # Make the request + response = await client.undelete_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UndeleteServiceAccountRequest, dict]]): + The request object. The service account undelete request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.UndeleteServiceAccountResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UndeleteServiceAccountRequest): + request = iam.UndeleteServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def enable_service_account( + self, + request: Optional[Union[iam.EnableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_enable_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountRequest( + ) + + # Make the request + await client.enable_service_account(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.EnableServiceAccountRequest, dict]]): + The request object. The service account enable request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.EnableServiceAccountRequest): + request = iam.EnableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.enable_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def disable_service_account( + self, + request: Optional[Union[iam.DisableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_disable_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountRequest( + ) + + # Make the request + await client.disable_service_account(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DisableServiceAccountRequest, dict]]): + The request object. The service account disable request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DisableServiceAccountRequest): + request = iam.DisableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.disable_service_account + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_service_account_keys( + self, + request: Optional[Union[iam.ListServiceAccountKeysRequest, dict]] = None, + *, + name: Optional[str] = None, + key_types: Optional[ + MutableSequence[iam.ListServiceAccountKeysRequest.KeyType] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ListServiceAccountKeysResponse: + r"""Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_list_service_account_keys(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Make the request + response = await client.list_service_account_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest, dict]]): + The request object. The service account keys list + request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID``, will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_types (:class:`MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]`): + Filters the types of keys the user + wants to include in the list response. + Duplicate key types are not allowed. If + no key type is provided, all keys are + returned. + + This corresponds to the ``key_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ListServiceAccountKeysResponse: + The service account keys list + response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, key_types] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ListServiceAccountKeysRequest): + request = iam.ListServiceAccountKeysRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if key_types: + request.key_types.extend(key_types) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_service_account_keys + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service_account_key( + self, + request: Optional[Union[iam.GetServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + public_key_type: Optional[iam.ServiceAccountPublicKeyType] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccountKey: + r"""Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_get_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.GetServiceAccountKeyRequest, dict]]): + The request object. The service account key get by id + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_key_type (:class:`google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType`): + Optional. The output format of the public key. The + default is ``TYPE_NONE``, which means that the public + key is not returned. + + This corresponds to the ``public_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, public_key_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.GetServiceAccountKeyRequest): + request = iam.GetServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if public_key_type is not None: + request.public_key_type = public_key_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service_account_key( + self, + request: Optional[Union[iam.CreateServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + private_key_type: Optional[iam.ServiceAccountPrivateKeyType] = None, + key_algorithm: Optional[iam.ServiceAccountKeyAlgorithm] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccountKey: + r"""Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_create_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.create_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.CreateServiceAccountKeyRequest, dict]]): + The request object. The service account key create + request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + private_key_type (:class:`google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType`): + The output format of the private key. The default value + is ``TYPE_GOOGLE_CREDENTIALS_FILE``, which is the Google + Credentials File format. + + This corresponds to the ``private_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_algorithm (:class:`google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm`): + Which type of key and algorithm to + use for the key. The default is + currently a 2K RSA key. However this + may change in the future. + + This corresponds to the ``key_algorithm`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, private_key_type, key_algorithm] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.CreateServiceAccountKeyRequest): + request = iam.CreateServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if private_key_type is not None: + request.private_key_type = private_key_type + if key_algorithm is not None: + request.key_algorithm = key_algorithm + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def upload_service_account_key( + self, + request: Optional[Union[iam.UploadServiceAccountKeyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccountKey: + r"""Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_upload_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UploadServiceAccountKeyRequest( + ) + + # Make the request + response = await client.upload_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UploadServiceAccountKeyRequest, dict]]): + The request object. The service account key upload + request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UploadServiceAccountKeyRequest): + request = iam.UploadServiceAccountKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.upload_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_service_account_key( + self, + request: Optional[Union[iam.DeleteServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_delete_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.delete_service_account_key(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountKeyRequest, dict]]): + The request object. The service account key delete + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DeleteServiceAccountKeyRequest): + request = iam.DeleteServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def disable_service_account_key( + self, + request: Optional[Union[iam.DisableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_disable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.disable_service_account_key(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DisableServiceAccountKeyRequest, dict]]): + The request object. The service account key disable + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DisableServiceAccountKeyRequest): + request = iam.DisableServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.disable_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def enable_service_account_key( + self, + request: Optional[Union[iam.EnableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_enable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.enable_service_account_key(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.EnableServiceAccountKeyRequest, dict]]): + The request object. The service account key enable + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.EnableServiceAccountKeyRequest): + request = iam.EnableServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.enable_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def sign_blob( + self, + request: Optional[Union[iam.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + bytes_to_sign: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.SignBlobResponse: + r"""**Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_sign_blob(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignBlobRequest( + name="name_value", + bytes_to_sign=b'bytes_to_sign_blob', + ) + + # Make the request + response = await client.sign_blob(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.SignBlobRequest, dict]]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob request. + name (:class:`str`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bytes_to_sign (:class:`bytes`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The bytes to sign. + + This corresponds to the ``bytes_to_sign`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.SignBlobResponse: + Deprecated. [Migrate to Service Account Credentials + API](https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign blob response. + + """ + warnings.warn("IAMAsyncClient.sign_blob is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, bytes_to_sign] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.SignBlobRequest): + request = iam.SignBlobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if bytes_to_sign is not None: + request.bytes_to_sign = bytes_to_sign + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.sign_blob + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def sign_jwt( + self, + request: Optional[Union[iam.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.SignJwtResponse: + r"""**Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_sign_jwt(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = await client.sign_jwt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.SignJwtRequest, dict]]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT request. + name (:class:`str`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`str`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The JWT payload to sign. Must be a serialized JSON + object that contains a JWT Claims Set. For example: + ``{"sub": "user@example.com", "iat": 313435}`` + + If the JWT Claims Set contains an expiration time + (``exp``) claim, it must be an integer timestamp that is + not in the past and no more than 12 hours in the future. + + If the JWT Claims Set does not contain an expiration + time (``exp``) claim, this claim is added automatically, + with a timestamp that is 1 hour in the future. + + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.SignJwtResponse: + Deprecated. [Migrate to Service Account Credentials + API](https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign JWT response. + + """ + warnings.warn("IAMAsyncClient.sign_jwt is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, payload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.SignJwtRequest): + request = iam.SignJwtRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.sign_jwt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_iam_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.set_iam_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource, permissions] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_grantable_roles( + self, + request: Optional[Union[iam.QueryGrantableRolesRequest, dict]] = None, + *, + full_resource_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.QueryGrantableRolesAsyncPager: + r"""Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_query_grantable_roles(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + ) + + # Make the request + page_result = client.query_grantable_roles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest, dict]]): + The request object. The grantable role query request. + full_resource_name (:class:`str`): + Required. The full resource name to query from the list + of grantable roles. + + The name follows the Google Cloud Platform resource + format. For example, a Cloud Platform project with id + ``my-project`` will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + + This corresponds to the ``full_resource_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryGrantableRolesAsyncPager: + The grantable role query response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [full_resource_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.QueryGrantableRolesRequest): + request = iam.QueryGrantableRolesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if full_resource_name is not None: + request.full_resource_name = full_resource_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_grantable_roles + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.QueryGrantableRolesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_roles( + self, + request: Optional[Union[iam.ListRolesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRolesAsyncPager: + r"""Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_list_roles(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListRolesRequest( + ) + + # Make the request + page_result = client.list_roles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ListRolesRequest, dict]]): + The request object. The request to get all roles defined + under a resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListRolesAsyncPager: + The response containing the roles + defined under a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ListRolesRequest): + request = iam.ListRolesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_roles + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRolesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_role( + self, + request: Optional[Union[iam.GetRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Gets the definition of a [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_get_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetRoleRequest( + ) + + # Make the request + response = await client.get_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.GetRoleRequest, dict]]): + The request object. The request to get the definition of + an existing role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.GetRoleRequest): + request = iam.GetRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_role( + self, + request: Optional[Union[iam.CreateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Creates a new custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_create_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateRoleRequest( + ) + + # Make the request + response = await client.create_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.CreateRoleRequest, dict]]): + The request object. The request to create a new role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.CreateRoleRequest): + request = iam.CreateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_role + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_role( + self, + request: Optional[Union[iam.UpdateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_update_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UpdateRoleRequest( + ) + + # Make the request + response = await client.update_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UpdateRoleRequest, dict]]): + The request object. The request to update a role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UpdateRoleRequest): + request = iam.UpdateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_role + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_role( + self, + request: Optional[Union[iam.DeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but they + have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_delete_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteRoleRequest( + ) + + # Make the request + response = await client.delete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DeleteRoleRequest, dict]]): + The request object. The request to delete an existing + role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DeleteRoleRequest): + request = iam.DeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_role + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def undelete_role( + self, + request: Optional[Union[iam.UndeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Undeletes a custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_undelete_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteRoleRequest( + ) + + # Make the request + response = await client.undelete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UndeleteRoleRequest, dict]]): + The request object. The request to undelete an existing + role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UndeleteRoleRequest): + request = iam.UndeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_role + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_testable_permissions( + self, + request: Optional[Union[iam.QueryTestablePermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.QueryTestablePermissionsAsyncPager: + r"""Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_query_testable_permissions(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryTestablePermissionsRequest( + ) + + # Make the request + page_result = client.query_testable_permissions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest, dict]]): + The request object. A request to get permissions which + can be tested on a resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryTestablePermissionsAsyncPager: + The response containing permissions + which can be tested on a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.QueryTestablePermissionsRequest): + request = iam.QueryTestablePermissionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_testable_permissions + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.QueryTestablePermissionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_auditable_services( + self, + request: Optional[Union[iam.QueryAuditableServicesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.QueryAuditableServicesResponse: + r"""Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_query_auditable_services(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryAuditableServicesRequest( + ) + + # Make the request + response = await client.query_auditable_services(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.QueryAuditableServicesRequest, dict]]): + The request object. A request to get the list of + auditable services for a resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse: + A response containing a list of + auditable services for a resource. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.QueryAuditableServicesRequest): + request = iam.QueryAuditableServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_auditable_services + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def lint_policy( + self, + request: Optional[Union[iam.LintPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.LintPolicyResponse: + r"""Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_lint_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.LintPolicyRequest( + ) + + # Make the request + response = await client.lint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.LintPolicyRequest, dict]]): + The request object. The request to lint a Cloud IAM + policy object. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.LintPolicyResponse: + The response of a lint operation. An + empty response indicates the operation + was able to fully execute and no lint + issue was found. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.LintPolicyRequest): + request = iam.LintPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.lint_policy + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "IAMAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("IAMAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/client.py new file mode 100644 index 0000000000000000000000000000000000000000..c465ac99dc88e03bcbdeb86605eed48214522dd2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/client.py @@ -0,0 +1,4334 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_admin_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.iam_admin_v1.services.iam import pagers +from google.cloud.iam_admin_v1.types import iam + +from .transports.base import DEFAULT_CLIENT_INFO, IAMTransport +from .transports.grpc import IAMGrpcTransport +from .transports.grpc_asyncio import IAMGrpcAsyncIOTransport + + +class IAMClientMeta(type): + """Metaclass for the IAM client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[IAMTransport]] + _transport_registry["grpc"] = IAMGrpcTransport + _transport_registry["grpc_asyncio"] = IAMGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[IAMTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class IAMClient(metaclass=IAMClientMeta): + """Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> IAMTransport: + """Returns the transport used by the client instance. + + Returns: + IAMTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def key_path( + project: str, + service_account: str, + key: str, + ) -> str: + """Returns a fully-qualified key string.""" + return "projects/{project}/serviceAccounts/{service_account}/keys/{key}".format( + project=project, + service_account=service_account, + key=key, + ) + + @staticmethod + def parse_key_path(path: str) -> Dict[str, str]: + """Parses a key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)/keys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_account_path( + project: str, + service_account: str, + ) -> str: + """Returns a fully-qualified service_account string.""" + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + + @staticmethod + def parse_service_account_path(path: str) -> Dict[str, str]: + """Parses a service_account path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = IAMClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = IAMClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = IAMClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = IAMClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = IAMClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = IAMClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMTransport, Callable[..., IAMTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the iam client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,IAMTransport,Callable[..., IAMTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the IAMTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + IAMClient._read_environment_variables() + ) + self._client_cert_source = IAMClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = IAMClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, IAMTransport) + if transport_provided: + # transport is a IAMTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(IAMTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or IAMClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[Type[IAMTransport], Callable[..., IAMTransport]] = ( + IAMClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., IAMTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam.admin_v1.IAMClient`.", + extra={ + "serviceName": "google.iam.admin.v1.IAM", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.admin.v1.IAM", + "credentialsType": None, + }, + ) + + def list_service_accounts( + self, + request: Optional[Union[iam.ListServiceAccountsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListServiceAccountsPager: + r"""Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_list_service_accounts(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_service_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ListServiceAccountsRequest, dict]): + The request object. The service account list request. + name (str): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListServiceAccountsPager: + The service account list response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ListServiceAccountsRequest): + request = iam.ListServiceAccountsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_service_accounts] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServiceAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service_account( + self, + request: Optional[Union[iam.GetServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_get_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.GetServiceAccountRequest, dict]): + The request object. The service account get request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.GetServiceAccountRequest): + request = iam.GetServiceAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_service_account( + self, + request: Optional[Union[iam.CreateServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + account_id: Optional[str] = None, + service_account: Optional[iam.ServiceAccount] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_create_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Make the request + response = client.create_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.CreateServiceAccountRequest, dict]): + The request object. The service account create request. + name (str): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + account_id (str): + Required. The account id that is used to generate the + service account email address and a stable unique id. It + is unique within a project, must be 6-30 characters + long, and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])`` to comply with RFC1035. + + This corresponds to the ``account_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_account (google.cloud.iam_admin_v1.types.ServiceAccount): + The [ServiceAccount][google.iam.admin.v1.ServiceAccount] + resource to create. Currently, only the following values + are user assignable: ``display_name`` and + ``description``. + + This corresponds to the ``service_account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, account_id, service_account] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.CreateServiceAccountRequest): + request = iam.CreateServiceAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if account_id is not None: + request.account_id = account_id + if service_account is not None: + request.service_account = service_account + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service_account( + self, + request: Optional[Union[iam.ServiceAccount, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""**Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_update_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ServiceAccount( + ) + + # Make the request + response = client.update_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ServiceAccount, dict]): + The request object. An IAM service account. + + A service account is an account for an application or a + virtual machine (VM) instance, not a person. You can use + a service account to call Google APIs. To learn more, + read the `overview of service + accounts `__. + + When you create a service account, you specify the + project ID that owns the service account, as well as a + name that must be unique within the project. IAM uses + these values to create an email address that identifies + the service account. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ServiceAccount): + request = iam.ServiceAccount(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def patch_service_account( + self, + request: Optional[Union[iam.PatchServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccount: + r"""Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_patch_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.PatchServiceAccountRequest( + ) + + # Make the request + response = client.patch_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.PatchServiceAccountRequest, dict]): + The request object. The service account patch request. + + You can patch only the ``display_name`` and + ``description`` fields. You must use the ``update_mask`` + field to specify which of these fields you want to + patch. + + Only the fields specified in the request are guaranteed + to be returned in the response. Other fields may be + empty in the response. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.PatchServiceAccountRequest): + request = iam.PatchServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("service_account.name", request.service_account.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_service_account( + self, + request: Optional[Union[iam.DeleteServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_delete_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_service_account(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountRequest, dict]): + The request object. The service account delete request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DeleteServiceAccountRequest): + request = iam.DeleteServiceAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def undelete_service_account( + self, + request: Optional[Union[iam.UndeleteServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.UndeleteServiceAccountResponse: + r"""Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_undelete_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteServiceAccountRequest( + ) + + # Make the request + response = client.undelete_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UndeleteServiceAccountRequest, dict]): + The request object. The service account undelete request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.UndeleteServiceAccountResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UndeleteServiceAccountRequest): + request = iam.UndeleteServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def enable_service_account( + self, + request: Optional[Union[iam.EnableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_enable_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountRequest( + ) + + # Make the request + client.enable_service_account(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.EnableServiceAccountRequest, dict]): + The request object. The service account enable request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.EnableServiceAccountRequest): + request = iam.EnableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.enable_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def disable_service_account( + self, + request: Optional[Union[iam.DisableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_disable_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountRequest( + ) + + # Make the request + client.disable_service_account(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DisableServiceAccountRequest, dict]): + The request object. The service account disable request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DisableServiceAccountRequest): + request = iam.DisableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.disable_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_service_account_keys( + self, + request: Optional[Union[iam.ListServiceAccountKeysRequest, dict]] = None, + *, + name: Optional[str] = None, + key_types: Optional[ + MutableSequence[iam.ListServiceAccountKeysRequest.KeyType] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ListServiceAccountKeysResponse: + r"""Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_list_service_account_keys(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Make the request + response = client.list_service_account_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest, dict]): + The request object. The service account keys list + request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID``, will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_types (MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]): + Filters the types of keys the user + wants to include in the list response. + Duplicate key types are not allowed. If + no key type is provided, all keys are + returned. + + This corresponds to the ``key_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ListServiceAccountKeysResponse: + The service account keys list + response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, key_types] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ListServiceAccountKeysRequest): + request = iam.ListServiceAccountKeysRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if key_types is not None: + request.key_types = key_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_service_account_keys + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service_account_key( + self, + request: Optional[Union[iam.GetServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + public_key_type: Optional[iam.ServiceAccountPublicKeyType] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccountKey: + r"""Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_get_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.GetServiceAccountKeyRequest, dict]): + The request object. The service account key get by id + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType): + Optional. The output format of the public key. The + default is ``TYPE_NONE``, which means that the public + key is not returned. + + This corresponds to the ``public_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, public_key_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.GetServiceAccountKeyRequest): + request = iam.GetServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if public_key_type is not None: + request.public_key_type = public_key_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_service_account_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_service_account_key( + self, + request: Optional[Union[iam.CreateServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + private_key_type: Optional[iam.ServiceAccountPrivateKeyType] = None, + key_algorithm: Optional[iam.ServiceAccountKeyAlgorithm] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccountKey: + r"""Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_create_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = client.create_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.CreateServiceAccountKeyRequest, dict]): + The request object. The service account key create + request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + private_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType): + The output format of the private key. The default value + is ``TYPE_GOOGLE_CREDENTIALS_FILE``, which is the Google + Credentials File format. + + This corresponds to the ``private_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_algorithm (google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm): + Which type of key and algorithm to + use for the key. The default is + currently a 2K RSA key. However this + may change in the future. + + This corresponds to the ``key_algorithm`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, private_key_type, key_algorithm] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.CreateServiceAccountKeyRequest): + request = iam.CreateServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if private_key_type is not None: + request.private_key_type = private_key_type + if key_algorithm is not None: + request.key_algorithm = key_algorithm + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def upload_service_account_key( + self, + request: Optional[Union[iam.UploadServiceAccountKeyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.ServiceAccountKey: + r"""Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_upload_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UploadServiceAccountKeyRequest( + ) + + # Make the request + response = client.upload_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UploadServiceAccountKeyRequest, dict]): + The request object. The service account key upload + request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UploadServiceAccountKeyRequest): + request = iam.UploadServiceAccountKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.upload_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_service_account_key( + self, + request: Optional[Union[iam.DeleteServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_delete_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.delete_service_account_key(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountKeyRequest, dict]): + The request object. The service account key delete + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DeleteServiceAccountKeyRequest): + request = iam.DeleteServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def disable_service_account_key( + self, + request: Optional[Union[iam.DisableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_disable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.disable_service_account_key(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DisableServiceAccountKeyRequest, dict]): + The request object. The service account key disable + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DisableServiceAccountKeyRequest): + request = iam.DisableServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.disable_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def enable_service_account_key( + self, + request: Optional[Union[iam.EnableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_enable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.enable_service_account_key(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.EnableServiceAccountKeyRequest, dict]): + The request object. The service account key enable + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.EnableServiceAccountKeyRequest): + request = iam.EnableServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.enable_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def sign_blob( + self, + request: Optional[Union[iam.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + bytes_to_sign: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.SignBlobResponse: + r"""**Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_sign_blob(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignBlobRequest( + name="name_value", + bytes_to_sign=b'bytes_to_sign_blob', + ) + + # Make the request + response = client.sign_blob(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.SignBlobRequest, dict]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob request. + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bytes_to_sign (bytes): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The bytes to sign. + + This corresponds to the ``bytes_to_sign`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.SignBlobResponse: + Deprecated. [Migrate to Service Account Credentials + API](https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign blob response. + + """ + warnings.warn("IAMClient.sign_blob is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, bytes_to_sign] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.SignBlobRequest): + request = iam.SignBlobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if bytes_to_sign is not None: + request.bytes_to_sign = bytes_to_sign + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.sign_blob] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def sign_jwt( + self, + request: Optional[Union[iam.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.SignJwtResponse: + r"""**Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_sign_jwt(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = client.sign_jwt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.SignJwtRequest, dict]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT request. + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The JWT payload to sign. Must be a serialized JSON + object that contains a JWT Claims Set. For example: + ``{"sub": "user@example.com", "iat": 313435}`` + + If the JWT Claims Set contains an expiration time + (``exp``) claim, it must be an integer timestamp that is + not in the past and no more than 12 hours in the future. + + If the JWT Claims Set does not contain an expiration + time (``exp``) claim, this claim is added automatically, + with a timestamp that is 1 hour in the future. + + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.SignJwtResponse: + Deprecated. [Migrate to Service Account Credentials + API](https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign JWT response. + + """ + warnings.warn("IAMClient.sign_jwt is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, payload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.SignJwtRequest): + request = iam.SignJwtRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.sign_jwt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource, permissions] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_grantable_roles( + self, + request: Optional[Union[iam.QueryGrantableRolesRequest, dict]] = None, + *, + full_resource_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.QueryGrantableRolesPager: + r"""Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_query_grantable_roles(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + ) + + # Make the request + page_result = client.query_grantable_roles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest, dict]): + The request object. The grantable role query request. + full_resource_name (str): + Required. The full resource name to query from the list + of grantable roles. + + The name follows the Google Cloud Platform resource + format. For example, a Cloud Platform project with id + ``my-project`` will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + + This corresponds to the ``full_resource_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryGrantableRolesPager: + The grantable role query response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [full_resource_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.QueryGrantableRolesRequest): + request = iam.QueryGrantableRolesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if full_resource_name is not None: + request.full_resource_name = full_resource_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_grantable_roles] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.QueryGrantableRolesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_roles( + self, + request: Optional[Union[iam.ListRolesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRolesPager: + r"""Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_list_roles(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListRolesRequest( + ) + + # Make the request + page_result = client.list_roles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ListRolesRequest, dict]): + The request object. The request to get all roles defined + under a resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListRolesPager: + The response containing the roles + defined under a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.ListRolesRequest): + request = iam.ListRolesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_roles] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRolesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_role( + self, + request: Optional[Union[iam.GetRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Gets the definition of a [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_get_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetRoleRequest( + ) + + # Make the request + response = client.get_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.GetRoleRequest, dict]): + The request object. The request to get the definition of + an existing role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.GetRoleRequest): + request = iam.GetRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_role( + self, + request: Optional[Union[iam.CreateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Creates a new custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_create_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateRoleRequest( + ) + + # Make the request + response = client.create_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.CreateRoleRequest, dict]): + The request object. The request to create a new role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.CreateRoleRequest): + request = iam.CreateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_role( + self, + request: Optional[Union[iam.UpdateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_update_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UpdateRoleRequest( + ) + + # Make the request + response = client.update_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UpdateRoleRequest, dict]): + The request object. The request to update a role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UpdateRoleRequest): + request = iam.UpdateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_role( + self, + request: Optional[Union[iam.DeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but they + have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_delete_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteRoleRequest( + ) + + # Make the request + response = client.delete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DeleteRoleRequest, dict]): + The request object. The request to delete an existing + role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.DeleteRoleRequest): + request = iam.DeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def undelete_role( + self, + request: Optional[Union[iam.UndeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.Role: + r"""Undeletes a custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_undelete_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteRoleRequest( + ) + + # Make the request + response = client.undelete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UndeleteRoleRequest, dict]): + The request object. The request to undelete an existing + role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.UndeleteRoleRequest): + request = iam.UndeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_testable_permissions( + self, + request: Optional[Union[iam.QueryTestablePermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.QueryTestablePermissionsPager: + r"""Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_query_testable_permissions(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryTestablePermissionsRequest( + ) + + # Make the request + page_result = client.query_testable_permissions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest, dict]): + The request object. A request to get permissions which + can be tested on a resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryTestablePermissionsPager: + The response containing permissions + which can be tested on a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.QueryTestablePermissionsRequest): + request = iam.QueryTestablePermissionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.query_testable_permissions + ] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.QueryTestablePermissionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_auditable_services( + self, + request: Optional[Union[iam.QueryAuditableServicesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.QueryAuditableServicesResponse: + r"""Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_query_auditable_services(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryAuditableServicesRequest( + ) + + # Make the request + response = client.query_auditable_services(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.QueryAuditableServicesRequest, dict]): + The request object. A request to get the list of + auditable services for a resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse: + A response containing a list of + auditable services for a resource. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.QueryAuditableServicesRequest): + request = iam.QueryAuditableServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_auditable_services] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def lint_policy( + self, + request: Optional[Union[iam.LintPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam.LintPolicyResponse: + r"""Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_lint_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.LintPolicyRequest( + ) + + # Make the request + response = client.lint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.LintPolicyRequest, dict]): + The request object. The request to lint a Cloud IAM + policy object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_admin_v1.types.LintPolicyResponse: + The response of a lint operation. An + empty response indicates the operation + was able to fully execute and no lint + issue was found. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, iam.LintPolicyRequest): + request = iam.LintPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lint_policy] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "IAMClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("IAMClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd5d2791b719cea555bb9c3aff79a2a5a5491b7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/pagers.py @@ -0,0 +1,665 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_admin_v1.types import iam + + +class ListServiceAccountsPager: + """A pager for iterating through ``list_service_accounts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServiceAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.ListServiceAccountsResponse], + request: iam.ListServiceAccountsRequest, + response: iam.ListServiceAccountsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListServiceAccountsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListServiceAccountsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.ListServiceAccountsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.ListServiceAccountsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[iam.ServiceAccount]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListServiceAccountsAsyncPager: + """A pager for iterating through ``list_service_accounts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServiceAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.ListServiceAccountsResponse]], + request: iam.ListServiceAccountsRequest, + response: iam.ListServiceAccountsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListServiceAccountsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListServiceAccountsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.ListServiceAccountsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.ListServiceAccountsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.ServiceAccount]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryGrantableRolesPager: + """A pager for iterating through ``query_grantable_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``QueryGrantableRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.QueryGrantableRolesResponse], + request: iam.QueryGrantableRolesRequest, + response: iam.QueryGrantableRolesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.QueryGrantableRolesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.QueryGrantableRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[iam.Role]: + for page in self.pages: + yield from page.roles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryGrantableRolesAsyncPager: + """A pager for iterating through ``query_grantable_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``QueryGrantableRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.QueryGrantableRolesResponse]], + request: iam.QueryGrantableRolesRequest, + response: iam.QueryGrantableRolesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.QueryGrantableRolesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.QueryGrantableRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.Role]: + async def async_generator(): + async for page in self.pages: + for response in page.roles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRolesPager: + """A pager for iterating through ``list_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.ListRolesResponse], + request: iam.ListRolesRequest, + response: iam.ListRolesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListRolesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.ListRolesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.ListRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[iam.Role]: + for page in self.pages: + yield from page.roles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRolesAsyncPager: + """A pager for iterating through ``list_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.ListRolesResponse]], + request: iam.ListRolesRequest, + response: iam.ListRolesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListRolesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.ListRolesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.ListRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.Role]: + async def async_generator(): + async for page in self.pages: + for response in page.roles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryTestablePermissionsPager: + """A pager for iterating through ``query_testable_permissions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``permissions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``QueryTestablePermissions`` requests and continue to iterate + through the ``permissions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.QueryTestablePermissionsResponse], + request: iam.QueryTestablePermissionsRequest, + response: iam.QueryTestablePermissionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.QueryTestablePermissionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.QueryTestablePermissionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[iam.Permission]: + for page in self.pages: + yield from page.permissions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryTestablePermissionsAsyncPager: + """A pager for iterating through ``query_testable_permissions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``permissions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``QueryTestablePermissions`` requests and continue to iterate + through the ``permissions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.QueryTestablePermissionsResponse]], + request: iam.QueryTestablePermissionsRequest, + response: iam.QueryTestablePermissionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = iam.QueryTestablePermissionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.QueryTestablePermissionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.Permission]: + async def async_generator(): + async for page in self.pages: + for response in page.permissions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae028f1edceda01f8aa516f78d212f5748d3a84 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import IAMTransport +from .grpc import IAMGrpcTransport +from .grpc_asyncio import IAMGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IAMTransport]] +_transport_registry["grpc"] = IAMGrpcTransport +_transport_registry["grpc_asyncio"] = IAMGrpcAsyncIOTransport + +__all__ = ( + "IAMTransport", + "IAMGrpcTransport", + "IAMGrpcAsyncIOTransport", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..bc215de42e007f797ea5bb6060c6566985d76d7f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/base.py @@ -0,0 +1,670 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_admin_v1 import gapic_version as package_version +from google.cloud.iam_admin_v1.types import iam + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class IAMTransport(abc.ABC): + """Abstract transport class for IAM.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_service_accounts: gapic_v1.method.wrap_method( + self.list_service_accounts, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_service_account: gapic_v1.method.wrap_method( + self.get_service_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_service_account: gapic_v1.method.wrap_method( + self.create_service_account, + default_timeout=60.0, + client_info=client_info, + ), + self.update_service_account: gapic_v1.method.wrap_method( + self.update_service_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.patch_service_account: gapic_v1.method.wrap_method( + self.patch_service_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_account: gapic_v1.method.wrap_method( + self.delete_service_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.undelete_service_account: gapic_v1.method.wrap_method( + self.undelete_service_account, + default_timeout=None, + client_info=client_info, + ), + self.enable_service_account: gapic_v1.method.wrap_method( + self.enable_service_account, + default_timeout=None, + client_info=client_info, + ), + self.disable_service_account: gapic_v1.method.wrap_method( + self.disable_service_account, + default_timeout=None, + client_info=client_info, + ), + self.list_service_account_keys: gapic_v1.method.wrap_method( + self.list_service_account_keys, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_service_account_key: gapic_v1.method.wrap_method( + self.get_service_account_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_service_account_key: gapic_v1.method.wrap_method( + self.create_service_account_key, + default_timeout=60.0, + client_info=client_info, + ), + self.upload_service_account_key: gapic_v1.method.wrap_method( + self.upload_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_account_key: gapic_v1.method.wrap_method( + self.delete_service_account_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_service_account_key: gapic_v1.method.wrap_method( + self.disable_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.enable_service_account_key: gapic_v1.method.wrap_method( + self.enable_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.sign_blob: gapic_v1.method.wrap_method( + self.sign_blob, + default_timeout=60.0, + client_info=client_info, + ), + self.sign_jwt: gapic_v1.method.wrap_method( + self.sign_jwt, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=60.0, + client_info=client_info, + ), + self.query_grantable_roles: gapic_v1.method.wrap_method( + self.query_grantable_roles, + default_timeout=60.0, + client_info=client_info, + ), + self.list_roles: gapic_v1.method.wrap_method( + self.list_roles, + default_timeout=None, + client_info=client_info, + ), + self.get_role: gapic_v1.method.wrap_method( + self.get_role, + default_timeout=None, + client_info=client_info, + ), + self.create_role: gapic_v1.method.wrap_method( + self.create_role, + default_timeout=None, + client_info=client_info, + ), + self.update_role: gapic_v1.method.wrap_method( + self.update_role, + default_timeout=None, + client_info=client_info, + ), + self.delete_role: gapic_v1.method.wrap_method( + self.delete_role, + default_timeout=None, + client_info=client_info, + ), + self.undelete_role: gapic_v1.method.wrap_method( + self.undelete_role, + default_timeout=None, + client_info=client_info, + ), + self.query_testable_permissions: gapic_v1.method.wrap_method( + self.query_testable_permissions, + default_timeout=None, + client_info=client_info, + ), + self.query_auditable_services: gapic_v1.method.wrap_method( + self.query_auditable_services, + default_timeout=None, + client_info=client_info, + ), + self.lint_policy: gapic_v1.method.wrap_method( + self.lint_policy, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_service_accounts( + self, + ) -> Callable[ + [iam.ListServiceAccountsRequest], + Union[ + iam.ListServiceAccountsResponse, Awaitable[iam.ListServiceAccountsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_service_account( + self, + ) -> Callable[ + [iam.GetServiceAccountRequest], + Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]], + ]: + raise NotImplementedError() + + @property + def create_service_account( + self, + ) -> Callable[ + [iam.CreateServiceAccountRequest], + Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]], + ]: + raise NotImplementedError() + + @property + def update_service_account( + self, + ) -> Callable[ + [iam.ServiceAccount], Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]] + ]: + raise NotImplementedError() + + @property + def patch_service_account( + self, + ) -> Callable[ + [iam.PatchServiceAccountRequest], + Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]], + ]: + raise NotImplementedError() + + @property + def delete_service_account( + self, + ) -> Callable[ + [iam.DeleteServiceAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def undelete_service_account( + self, + ) -> Callable[ + [iam.UndeleteServiceAccountRequest], + Union[ + iam.UndeleteServiceAccountResponse, + Awaitable[iam.UndeleteServiceAccountResponse], + ], + ]: + raise NotImplementedError() + + @property + def enable_service_account( + self, + ) -> Callable[ + [iam.EnableServiceAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def disable_service_account( + self, + ) -> Callable[ + [iam.DisableServiceAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_service_account_keys( + self, + ) -> Callable[ + [iam.ListServiceAccountKeysRequest], + Union[ + iam.ListServiceAccountKeysResponse, + Awaitable[iam.ListServiceAccountKeysResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_service_account_key( + self, + ) -> Callable[ + [iam.GetServiceAccountKeyRequest], + Union[iam.ServiceAccountKey, Awaitable[iam.ServiceAccountKey]], + ]: + raise NotImplementedError() + + @property + def create_service_account_key( + self, + ) -> Callable[ + [iam.CreateServiceAccountKeyRequest], + Union[iam.ServiceAccountKey, Awaitable[iam.ServiceAccountKey]], + ]: + raise NotImplementedError() + + @property + def upload_service_account_key( + self, + ) -> Callable[ + [iam.UploadServiceAccountKeyRequest], + Union[iam.ServiceAccountKey, Awaitable[iam.ServiceAccountKey]], + ]: + raise NotImplementedError() + + @property + def delete_service_account_key( + self, + ) -> Callable[ + [iam.DeleteServiceAccountKeyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def disable_service_account_key( + self, + ) -> Callable[ + [iam.DisableServiceAccountKeyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def enable_service_account_key( + self, + ) -> Callable[ + [iam.EnableServiceAccountKeyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def sign_blob( + self, + ) -> Callable[ + [iam.SignBlobRequest], + Union[iam.SignBlobResponse, Awaitable[iam.SignBlobResponse]], + ]: + raise NotImplementedError() + + @property + def sign_jwt( + self, + ) -> Callable[ + [iam.SignJwtRequest], Union[iam.SignJwtResponse, Awaitable[iam.SignJwtResponse]] + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def query_grantable_roles( + self, + ) -> Callable[ + [iam.QueryGrantableRolesRequest], + Union[ + iam.QueryGrantableRolesResponse, Awaitable[iam.QueryGrantableRolesResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_roles( + self, + ) -> Callable[ + [iam.ListRolesRequest], + Union[iam.ListRolesResponse, Awaitable[iam.ListRolesResponse]], + ]: + raise NotImplementedError() + + @property + def get_role( + self, + ) -> Callable[[iam.GetRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def create_role( + self, + ) -> Callable[[iam.CreateRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def update_role( + self, + ) -> Callable[[iam.UpdateRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def delete_role( + self, + ) -> Callable[[iam.DeleteRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def undelete_role( + self, + ) -> Callable[[iam.UndeleteRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def query_testable_permissions( + self, + ) -> Callable[ + [iam.QueryTestablePermissionsRequest], + Union[ + iam.QueryTestablePermissionsResponse, + Awaitable[iam.QueryTestablePermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def query_auditable_services( + self, + ) -> Callable[ + [iam.QueryAuditableServicesRequest], + Union[ + iam.QueryAuditableServicesResponse, + Awaitable[iam.QueryAuditableServicesResponse], + ], + ]: + raise NotImplementedError() + + @property + def lint_policy( + self, + ) -> Callable[ + [iam.LintPolicyRequest], + Union[iam.LintPolicyResponse, Awaitable[iam.LintPolicyResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("IAMTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..6feb1b205de66a5b349657c21de5b0e35a2b9d8c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/grpc.py @@ -0,0 +1,1343 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_admin_v1.types import iam + +from .base import DEFAULT_CLIENT_INFO, IAMTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.admin.v1.IAM", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.admin.v1.IAM", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class IAMGrpcTransport(IAMTransport): + """gRPC backend transport for IAM. + + Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_service_accounts( + self, + ) -> Callable[[iam.ListServiceAccountsRequest], iam.ListServiceAccountsResponse]: + r"""Return a callable for the list service accounts method over gRPC. + + Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + Returns: + Callable[[~.ListServiceAccountsRequest], + ~.ListServiceAccountsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_accounts" not in self._stubs: + self._stubs["list_service_accounts"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccounts", + request_serializer=iam.ListServiceAccountsRequest.serialize, + response_deserializer=iam.ListServiceAccountsResponse.deserialize, + ) + return self._stubs["list_service_accounts"] + + @property + def get_service_account( + self, + ) -> Callable[[iam.GetServiceAccountRequest], iam.ServiceAccount]: + r"""Return a callable for the get service account method over gRPC. + + Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.GetServiceAccountRequest], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account" not in self._stubs: + self._stubs["get_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccount", + request_serializer=iam.GetServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["get_service_account"] + + @property + def create_service_account( + self, + ) -> Callable[[iam.CreateServiceAccountRequest], iam.ServiceAccount]: + r"""Return a callable for the create service account method over gRPC. + + Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.CreateServiceAccountRequest], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account" not in self._stubs: + self._stubs["create_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccount", + request_serializer=iam.CreateServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["create_service_account"] + + @property + def update_service_account( + self, + ) -> Callable[[iam.ServiceAccount], iam.ServiceAccount]: + r"""Return a callable for the update service account method over gRPC. + + **Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + Returns: + Callable[[~.ServiceAccount], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service_account" not in self._stubs: + self._stubs["update_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateServiceAccount", + request_serializer=iam.ServiceAccount.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["update_service_account"] + + @property + def patch_service_account( + self, + ) -> Callable[[iam.PatchServiceAccountRequest], iam.ServiceAccount]: + r"""Return a callable for the patch service account method over gRPC. + + Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.PatchServiceAccountRequest], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "patch_service_account" not in self._stubs: + self._stubs["patch_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/PatchServiceAccount", + request_serializer=iam.PatchServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["patch_service_account"] + + @property + def delete_service_account( + self, + ) -> Callable[[iam.DeleteServiceAccountRequest], empty_pb2.Empty]: + r"""Return a callable for the delete service account method over gRPC. + + Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + Returns: + Callable[[~.DeleteServiceAccountRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account" not in self._stubs: + self._stubs["delete_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccount", + request_serializer=iam.DeleteServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_service_account"] + + @property + def undelete_service_account( + self, + ) -> Callable[ + [iam.UndeleteServiceAccountRequest], iam.UndeleteServiceAccountResponse + ]: + r"""Return a callable for the undelete service account method over gRPC. + + Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + Returns: + Callable[[~.UndeleteServiceAccountRequest], + ~.UndeleteServiceAccountResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_service_account" not in self._stubs: + self._stubs["undelete_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteServiceAccount", + request_serializer=iam.UndeleteServiceAccountRequest.serialize, + response_deserializer=iam.UndeleteServiceAccountResponse.deserialize, + ) + return self._stubs["undelete_service_account"] + + @property + def enable_service_account( + self, + ) -> Callable[[iam.EnableServiceAccountRequest], empty_pb2.Empty]: + r"""Return a callable for the enable service account method over gRPC. + + Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + Returns: + Callable[[~.EnableServiceAccountRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account" not in self._stubs: + self._stubs["enable_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccount", + request_serializer=iam.EnableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["enable_service_account"] + + @property + def disable_service_account( + self, + ) -> Callable[[iam.DisableServiceAccountRequest], empty_pb2.Empty]: + r"""Return a callable for the disable service account method over gRPC. + + Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + Returns: + Callable[[~.DisableServiceAccountRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account" not in self._stubs: + self._stubs["disable_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccount", + request_serializer=iam.DisableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["disable_service_account"] + + @property + def list_service_account_keys( + self, + ) -> Callable[ + [iam.ListServiceAccountKeysRequest], iam.ListServiceAccountKeysResponse + ]: + r"""Return a callable for the list service account keys method over gRPC. + + Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + Returns: + Callable[[~.ListServiceAccountKeysRequest], + ~.ListServiceAccountKeysResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_account_keys" not in self._stubs: + self._stubs["list_service_account_keys"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccountKeys", + request_serializer=iam.ListServiceAccountKeysRequest.serialize, + response_deserializer=iam.ListServiceAccountKeysResponse.deserialize, + ) + return self._stubs["list_service_account_keys"] + + @property + def get_service_account_key( + self, + ) -> Callable[[iam.GetServiceAccountKeyRequest], iam.ServiceAccountKey]: + r"""Return a callable for the get service account key method over gRPC. + + Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.GetServiceAccountKeyRequest], + ~.ServiceAccountKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account_key" not in self._stubs: + self._stubs["get_service_account_key"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccountKey", + request_serializer=iam.GetServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["get_service_account_key"] + + @property + def create_service_account_key( + self, + ) -> Callable[[iam.CreateServiceAccountKeyRequest], iam.ServiceAccountKey]: + r"""Return a callable for the create service account key method over gRPC. + + Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.CreateServiceAccountKeyRequest], + ~.ServiceAccountKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account_key" not in self._stubs: + self._stubs["create_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccountKey", + request_serializer=iam.CreateServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + ) + return self._stubs["create_service_account_key"] + + @property + def upload_service_account_key( + self, + ) -> Callable[[iam.UploadServiceAccountKeyRequest], iam.ServiceAccountKey]: + r"""Return a callable for the upload service account key method over gRPC. + + Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + Returns: + Callable[[~.UploadServiceAccountKeyRequest], + ~.ServiceAccountKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "upload_service_account_key" not in self._stubs: + self._stubs["upload_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UploadServiceAccountKey", + request_serializer=iam.UploadServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + ) + return self._stubs["upload_service_account_key"] + + @property + def delete_service_account_key( + self, + ) -> Callable[[iam.DeleteServiceAccountKeyRequest], empty_pb2.Empty]: + r"""Return a callable for the delete service account key method over gRPC. + + Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + Returns: + Callable[[~.DeleteServiceAccountKeyRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account_key" not in self._stubs: + self._stubs["delete_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccountKey", + request_serializer=iam.DeleteServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["delete_service_account_key"] + + @property + def disable_service_account_key( + self, + ) -> Callable[[iam.DisableServiceAccountKeyRequest], empty_pb2.Empty]: + r"""Return a callable for the disable service account key method over gRPC. + + Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + Returns: + Callable[[~.DisableServiceAccountKeyRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account_key" not in self._stubs: + self._stubs["disable_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccountKey", + request_serializer=iam.DisableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["disable_service_account_key"] + + @property + def enable_service_account_key( + self, + ) -> Callable[[iam.EnableServiceAccountKeyRequest], empty_pb2.Empty]: + r"""Return a callable for the enable service account key method over gRPC. + + Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.EnableServiceAccountKeyRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account_key" not in self._stubs: + self._stubs["enable_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccountKey", + request_serializer=iam.EnableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["enable_service_account_key"] + + @property + def sign_blob(self) -> Callable[[iam.SignBlobRequest], iam.SignBlobResponse]: + r"""Return a callable for the sign blob method over gRPC. + + **Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignBlobRequest], + ~.SignBlobResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignBlob", + request_serializer=iam.SignBlobRequest.serialize, + response_deserializer=iam.SignBlobResponse.deserialize, + ) + return self._stubs["sign_blob"] + + @property + def sign_jwt(self) -> Callable[[iam.SignJwtRequest], iam.SignJwtResponse]: + r"""Return a callable for the sign jwt method over gRPC. + + **Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignJwtRequest], + ~.SignJwtResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignJwt", + request_serializer=iam.SignJwtRequest.serialize, + response_deserializer=iam.SignJwtResponse.deserialize, + ) + return self._stubs["sign_jwt"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def query_grantable_roles( + self, + ) -> Callable[[iam.QueryGrantableRolesRequest], iam.QueryGrantableRolesResponse]: + r"""Return a callable for the query grantable roles method over gRPC. + + Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + Returns: + Callable[[~.QueryGrantableRolesRequest], + ~.QueryGrantableRolesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_grantable_roles" not in self._stubs: + self._stubs["query_grantable_roles"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryGrantableRoles", + request_serializer=iam.QueryGrantableRolesRequest.serialize, + response_deserializer=iam.QueryGrantableRolesResponse.deserialize, + ) + return self._stubs["query_grantable_roles"] + + @property + def list_roles(self) -> Callable[[iam.ListRolesRequest], iam.ListRolesResponse]: + r"""Return a callable for the list roles method over gRPC. + + Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + Returns: + Callable[[~.ListRolesRequest], + ~.ListRolesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_roles" not in self._stubs: + self._stubs["list_roles"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListRoles", + request_serializer=iam.ListRolesRequest.serialize, + response_deserializer=iam.ListRolesResponse.deserialize, + ) + return self._stubs["list_roles"] + + @property + def get_role(self) -> Callable[[iam.GetRoleRequest], iam.Role]: + r"""Return a callable for the get role method over gRPC. + + Gets the definition of a [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.GetRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_role" not in self._stubs: + self._stubs["get_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetRole", + request_serializer=iam.GetRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["get_role"] + + @property + def create_role(self) -> Callable[[iam.CreateRoleRequest], iam.Role]: + r"""Return a callable for the create role method over gRPC. + + Creates a new custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.CreateRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_role" not in self._stubs: + self._stubs["create_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateRole", + request_serializer=iam.CreateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["create_role"] + + @property + def update_role(self) -> Callable[[iam.UpdateRoleRequest], iam.Role]: + r"""Return a callable for the update role method over gRPC. + + Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UpdateRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_role" not in self._stubs: + self._stubs["update_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateRole", + request_serializer=iam.UpdateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["update_role"] + + @property + def delete_role(self) -> Callable[[iam.DeleteRoleRequest], iam.Role]: + r"""Return a callable for the delete role method over gRPC. + + Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but they + have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + Returns: + Callable[[~.DeleteRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_role" not in self._stubs: + self._stubs["delete_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteRole", + request_serializer=iam.DeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["delete_role"] + + @property + def undelete_role(self) -> Callable[[iam.UndeleteRoleRequest], iam.Role]: + r"""Return a callable for the undelete role method over gRPC. + + Undeletes a custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UndeleteRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_role" not in self._stubs: + self._stubs["undelete_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteRole", + request_serializer=iam.UndeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["undelete_role"] + + @property + def query_testable_permissions( + self, + ) -> Callable[ + [iam.QueryTestablePermissionsRequest], iam.QueryTestablePermissionsResponse + ]: + r"""Return a callable for the query testable permissions method over gRPC. + + Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + Returns: + Callable[[~.QueryTestablePermissionsRequest], + ~.QueryTestablePermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_testable_permissions" not in self._stubs: + self._stubs["query_testable_permissions"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryTestablePermissions", + request_serializer=iam.QueryTestablePermissionsRequest.serialize, + response_deserializer=iam.QueryTestablePermissionsResponse.deserialize, + ) + ) + return self._stubs["query_testable_permissions"] + + @property + def query_auditable_services( + self, + ) -> Callable[ + [iam.QueryAuditableServicesRequest], iam.QueryAuditableServicesResponse + ]: + r"""Return a callable for the query auditable services method over gRPC. + + Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + Returns: + Callable[[~.QueryAuditableServicesRequest], + ~.QueryAuditableServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_auditable_services" not in self._stubs: + self._stubs["query_auditable_services"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryAuditableServices", + request_serializer=iam.QueryAuditableServicesRequest.serialize, + response_deserializer=iam.QueryAuditableServicesResponse.deserialize, + ) + return self._stubs["query_auditable_services"] + + @property + def lint_policy(self) -> Callable[[iam.LintPolicyRequest], iam.LintPolicyResponse]: + r"""Return a callable for the lint policy method over gRPC. + + Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + Returns: + Callable[[~.LintPolicyRequest], + ~.LintPolicyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "lint_policy" not in self._stubs: + self._stubs["lint_policy"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/LintPolicy", + request_serializer=iam.LintPolicyRequest.serialize, + response_deserializer=iam.LintPolicyResponse.deserialize, + ) + return self._stubs["lint_policy"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("IAMGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..92ced69c6d65f8a56d16e56e0b8bacc31b1b75ed --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/services/iam/transports/grpc_asyncio.py @@ -0,0 +1,1606 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_admin_v1.types import iam + +from .base import DEFAULT_CLIENT_INFO, IAMTransport +from .grpc import IAMGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.admin.v1.IAM", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.admin.v1.IAM", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class IAMGrpcAsyncIOTransport(IAMTransport): + """gRPC AsyncIO backend transport for IAM. + + Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_service_accounts( + self, + ) -> Callable[ + [iam.ListServiceAccountsRequest], Awaitable[iam.ListServiceAccountsResponse] + ]: + r"""Return a callable for the list service accounts method over gRPC. + + Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + Returns: + Callable[[~.ListServiceAccountsRequest], + Awaitable[~.ListServiceAccountsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_accounts" not in self._stubs: + self._stubs["list_service_accounts"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccounts", + request_serializer=iam.ListServiceAccountsRequest.serialize, + response_deserializer=iam.ListServiceAccountsResponse.deserialize, + ) + return self._stubs["list_service_accounts"] + + @property + def get_service_account( + self, + ) -> Callable[[iam.GetServiceAccountRequest], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the get service account method over gRPC. + + Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.GetServiceAccountRequest], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account" not in self._stubs: + self._stubs["get_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccount", + request_serializer=iam.GetServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["get_service_account"] + + @property + def create_service_account( + self, + ) -> Callable[[iam.CreateServiceAccountRequest], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the create service account method over gRPC. + + Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.CreateServiceAccountRequest], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account" not in self._stubs: + self._stubs["create_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccount", + request_serializer=iam.CreateServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["create_service_account"] + + @property + def update_service_account( + self, + ) -> Callable[[iam.ServiceAccount], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the update service account method over gRPC. + + **Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + Returns: + Callable[[~.ServiceAccount], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service_account" not in self._stubs: + self._stubs["update_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateServiceAccount", + request_serializer=iam.ServiceAccount.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["update_service_account"] + + @property + def patch_service_account( + self, + ) -> Callable[[iam.PatchServiceAccountRequest], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the patch service account method over gRPC. + + Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.PatchServiceAccountRequest], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "patch_service_account" not in self._stubs: + self._stubs["patch_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/PatchServiceAccount", + request_serializer=iam.PatchServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["patch_service_account"] + + @property + def delete_service_account( + self, + ) -> Callable[[iam.DeleteServiceAccountRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete service account method over gRPC. + + Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + Returns: + Callable[[~.DeleteServiceAccountRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account" not in self._stubs: + self._stubs["delete_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccount", + request_serializer=iam.DeleteServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_service_account"] + + @property + def undelete_service_account( + self, + ) -> Callable[ + [iam.UndeleteServiceAccountRequest], + Awaitable[iam.UndeleteServiceAccountResponse], + ]: + r"""Return a callable for the undelete service account method over gRPC. + + Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + Returns: + Callable[[~.UndeleteServiceAccountRequest], + Awaitable[~.UndeleteServiceAccountResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_service_account" not in self._stubs: + self._stubs["undelete_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteServiceAccount", + request_serializer=iam.UndeleteServiceAccountRequest.serialize, + response_deserializer=iam.UndeleteServiceAccountResponse.deserialize, + ) + return self._stubs["undelete_service_account"] + + @property + def enable_service_account( + self, + ) -> Callable[[iam.EnableServiceAccountRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the enable service account method over gRPC. + + Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + Returns: + Callable[[~.EnableServiceAccountRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account" not in self._stubs: + self._stubs["enable_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccount", + request_serializer=iam.EnableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["enable_service_account"] + + @property + def disable_service_account( + self, + ) -> Callable[[iam.DisableServiceAccountRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the disable service account method over gRPC. + + Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + Returns: + Callable[[~.DisableServiceAccountRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account" not in self._stubs: + self._stubs["disable_service_account"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccount", + request_serializer=iam.DisableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["disable_service_account"] + + @property + def list_service_account_keys( + self, + ) -> Callable[ + [iam.ListServiceAccountKeysRequest], + Awaitable[iam.ListServiceAccountKeysResponse], + ]: + r"""Return a callable for the list service account keys method over gRPC. + + Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + Returns: + Callable[[~.ListServiceAccountKeysRequest], + Awaitable[~.ListServiceAccountKeysResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_account_keys" not in self._stubs: + self._stubs["list_service_account_keys"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccountKeys", + request_serializer=iam.ListServiceAccountKeysRequest.serialize, + response_deserializer=iam.ListServiceAccountKeysResponse.deserialize, + ) + return self._stubs["list_service_account_keys"] + + @property + def get_service_account_key( + self, + ) -> Callable[[iam.GetServiceAccountKeyRequest], Awaitable[iam.ServiceAccountKey]]: + r"""Return a callable for the get service account key method over gRPC. + + Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.GetServiceAccountKeyRequest], + Awaitable[~.ServiceAccountKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account_key" not in self._stubs: + self._stubs["get_service_account_key"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccountKey", + request_serializer=iam.GetServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["get_service_account_key"] + + @property + def create_service_account_key( + self, + ) -> Callable[ + [iam.CreateServiceAccountKeyRequest], Awaitable[iam.ServiceAccountKey] + ]: + r"""Return a callable for the create service account key method over gRPC. + + Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.CreateServiceAccountKeyRequest], + Awaitable[~.ServiceAccountKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account_key" not in self._stubs: + self._stubs["create_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccountKey", + request_serializer=iam.CreateServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + ) + return self._stubs["create_service_account_key"] + + @property + def upload_service_account_key( + self, + ) -> Callable[ + [iam.UploadServiceAccountKeyRequest], Awaitable[iam.ServiceAccountKey] + ]: + r"""Return a callable for the upload service account key method over gRPC. + + Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + Returns: + Callable[[~.UploadServiceAccountKeyRequest], + Awaitable[~.ServiceAccountKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "upload_service_account_key" not in self._stubs: + self._stubs["upload_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UploadServiceAccountKey", + request_serializer=iam.UploadServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + ) + return self._stubs["upload_service_account_key"] + + @property + def delete_service_account_key( + self, + ) -> Callable[[iam.DeleteServiceAccountKeyRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete service account key method over gRPC. + + Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + Returns: + Callable[[~.DeleteServiceAccountKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account_key" not in self._stubs: + self._stubs["delete_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccountKey", + request_serializer=iam.DeleteServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["delete_service_account_key"] + + @property + def disable_service_account_key( + self, + ) -> Callable[[iam.DisableServiceAccountKeyRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the disable service account key method over gRPC. + + Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + Returns: + Callable[[~.DisableServiceAccountKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account_key" not in self._stubs: + self._stubs["disable_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccountKey", + request_serializer=iam.DisableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["disable_service_account_key"] + + @property + def enable_service_account_key( + self, + ) -> Callable[[iam.EnableServiceAccountKeyRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the enable service account key method over gRPC. + + Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.EnableServiceAccountKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account_key" not in self._stubs: + self._stubs["enable_service_account_key"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccountKey", + request_serializer=iam.EnableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["enable_service_account_key"] + + @property + def sign_blob( + self, + ) -> Callable[[iam.SignBlobRequest], Awaitable[iam.SignBlobResponse]]: + r"""Return a callable for the sign blob method over gRPC. + + **Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignBlobRequest], + Awaitable[~.SignBlobResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignBlob", + request_serializer=iam.SignBlobRequest.serialize, + response_deserializer=iam.SignBlobResponse.deserialize, + ) + return self._stubs["sign_blob"] + + @property + def sign_jwt( + self, + ) -> Callable[[iam.SignJwtRequest], Awaitable[iam.SignJwtResponse]]: + r"""Return a callable for the sign jwt method over gRPC. + + **Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignJwtRequest], + Awaitable[~.SignJwtResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignJwt", + request_serializer=iam.SignJwtRequest.serialize, + response_deserializer=iam.SignJwtResponse.deserialize, + ) + return self._stubs["sign_jwt"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def query_grantable_roles( + self, + ) -> Callable[ + [iam.QueryGrantableRolesRequest], Awaitable[iam.QueryGrantableRolesResponse] + ]: + r"""Return a callable for the query grantable roles method over gRPC. + + Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + Returns: + Callable[[~.QueryGrantableRolesRequest], + Awaitable[~.QueryGrantableRolesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_grantable_roles" not in self._stubs: + self._stubs["query_grantable_roles"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryGrantableRoles", + request_serializer=iam.QueryGrantableRolesRequest.serialize, + response_deserializer=iam.QueryGrantableRolesResponse.deserialize, + ) + return self._stubs["query_grantable_roles"] + + @property + def list_roles( + self, + ) -> Callable[[iam.ListRolesRequest], Awaitable[iam.ListRolesResponse]]: + r"""Return a callable for the list roles method over gRPC. + + Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + Returns: + Callable[[~.ListRolesRequest], + Awaitable[~.ListRolesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_roles" not in self._stubs: + self._stubs["list_roles"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListRoles", + request_serializer=iam.ListRolesRequest.serialize, + response_deserializer=iam.ListRolesResponse.deserialize, + ) + return self._stubs["list_roles"] + + @property + def get_role(self) -> Callable[[iam.GetRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the get role method over gRPC. + + Gets the definition of a [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.GetRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_role" not in self._stubs: + self._stubs["get_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetRole", + request_serializer=iam.GetRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["get_role"] + + @property + def create_role(self) -> Callable[[iam.CreateRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the create role method over gRPC. + + Creates a new custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.CreateRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_role" not in self._stubs: + self._stubs["create_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateRole", + request_serializer=iam.CreateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["create_role"] + + @property + def update_role(self) -> Callable[[iam.UpdateRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the update role method over gRPC. + + Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UpdateRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_role" not in self._stubs: + self._stubs["update_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateRole", + request_serializer=iam.UpdateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["update_role"] + + @property + def delete_role(self) -> Callable[[iam.DeleteRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the delete role method over gRPC. + + Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but they + have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + Returns: + Callable[[~.DeleteRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_role" not in self._stubs: + self._stubs["delete_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteRole", + request_serializer=iam.DeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["delete_role"] + + @property + def undelete_role(self) -> Callable[[iam.UndeleteRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the undelete role method over gRPC. + + Undeletes a custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UndeleteRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_role" not in self._stubs: + self._stubs["undelete_role"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteRole", + request_serializer=iam.UndeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["undelete_role"] + + @property + def query_testable_permissions( + self, + ) -> Callable[ + [iam.QueryTestablePermissionsRequest], + Awaitable[iam.QueryTestablePermissionsResponse], + ]: + r"""Return a callable for the query testable permissions method over gRPC. + + Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + Returns: + Callable[[~.QueryTestablePermissionsRequest], + Awaitable[~.QueryTestablePermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_testable_permissions" not in self._stubs: + self._stubs["query_testable_permissions"] = ( + self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryTestablePermissions", + request_serializer=iam.QueryTestablePermissionsRequest.serialize, + response_deserializer=iam.QueryTestablePermissionsResponse.deserialize, + ) + ) + return self._stubs["query_testable_permissions"] + + @property + def query_auditable_services( + self, + ) -> Callable[ + [iam.QueryAuditableServicesRequest], + Awaitable[iam.QueryAuditableServicesResponse], + ]: + r"""Return a callable for the query auditable services method over gRPC. + + Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + Returns: + Callable[[~.QueryAuditableServicesRequest], + Awaitable[~.QueryAuditableServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_auditable_services" not in self._stubs: + self._stubs["query_auditable_services"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryAuditableServices", + request_serializer=iam.QueryAuditableServicesRequest.serialize, + response_deserializer=iam.QueryAuditableServicesResponse.deserialize, + ) + return self._stubs["query_auditable_services"] + + @property + def lint_policy( + self, + ) -> Callable[[iam.LintPolicyRequest], Awaitable[iam.LintPolicyResponse]]: + r"""Return a callable for the lint policy method over gRPC. + + Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + Returns: + Callable[[~.LintPolicyRequest], + Awaitable[~.LintPolicyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "lint_policy" not in self._stubs: + self._stubs["lint_policy"] = self._logged_channel.unary_unary( + "/google.iam.admin.v1.IAM/LintPolicy", + request_serializer=iam.LintPolicyRequest.serialize, + response_deserializer=iam.LintPolicyResponse.deserialize, + ) + return self._stubs["lint_policy"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_service_accounts: self._wrap_method( + self.list_service_accounts, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_service_account: self._wrap_method( + self.get_service_account, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_service_account: self._wrap_method( + self.create_service_account, + default_timeout=60.0, + client_info=client_info, + ), + self.update_service_account: self._wrap_method( + self.update_service_account, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.patch_service_account: self._wrap_method( + self.patch_service_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_account: self._wrap_method( + self.delete_service_account, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.undelete_service_account: self._wrap_method( + self.undelete_service_account, + default_timeout=None, + client_info=client_info, + ), + self.enable_service_account: self._wrap_method( + self.enable_service_account, + default_timeout=None, + client_info=client_info, + ), + self.disable_service_account: self._wrap_method( + self.disable_service_account, + default_timeout=None, + client_info=client_info, + ), + self.list_service_account_keys: self._wrap_method( + self.list_service_account_keys, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_service_account_key: self._wrap_method( + self.get_service_account_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_service_account_key: self._wrap_method( + self.create_service_account_key, + default_timeout=60.0, + client_info=client_info, + ), + self.upload_service_account_key: self._wrap_method( + self.upload_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_account_key: self._wrap_method( + self.delete_service_account_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_service_account_key: self._wrap_method( + self.disable_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.enable_service_account_key: self._wrap_method( + self.enable_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.sign_blob: self._wrap_method( + self.sign_blob, + default_timeout=60.0, + client_info=client_info, + ), + self.sign_jwt: self._wrap_method( + self.sign_jwt, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=60.0, + client_info=client_info, + ), + self.query_grantable_roles: self._wrap_method( + self.query_grantable_roles, + default_timeout=60.0, + client_info=client_info, + ), + self.list_roles: self._wrap_method( + self.list_roles, + default_timeout=None, + client_info=client_info, + ), + self.get_role: self._wrap_method( + self.get_role, + default_timeout=None, + client_info=client_info, + ), + self.create_role: self._wrap_method( + self.create_role, + default_timeout=None, + client_info=client_info, + ), + self.update_role: self._wrap_method( + self.update_role, + default_timeout=None, + client_info=client_info, + ), + self.delete_role: self._wrap_method( + self.delete_role, + default_timeout=None, + client_info=client_info, + ), + self.undelete_role: self._wrap_method( + self.undelete_role, + default_timeout=None, + client_info=client_info, + ), + self.query_testable_permissions: self._wrap_method( + self.query_testable_permissions, + default_timeout=None, + client_info=client_info, + ), + self.query_auditable_services: self._wrap_method( + self.query_auditable_services, + default_timeout=None, + client_info=client_info, + ), + self.lint_policy: self._wrap_method( + self.lint_policy, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("IAMGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63688b8fba3531a90e6a89860ca594f371de97b5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/__init__.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .audit_data import ( + AuditData, +) +from .iam import ( + CreateRoleRequest, + CreateServiceAccountKeyRequest, + CreateServiceAccountRequest, + DeleteRoleRequest, + DeleteServiceAccountKeyRequest, + DeleteServiceAccountRequest, + DisableServiceAccountKeyRequest, + DisableServiceAccountRequest, + EnableServiceAccountKeyRequest, + EnableServiceAccountRequest, + GetRoleRequest, + GetServiceAccountKeyRequest, + GetServiceAccountRequest, + LintPolicyRequest, + LintPolicyResponse, + LintResult, + ListRolesRequest, + ListRolesResponse, + ListServiceAccountKeysRequest, + ListServiceAccountKeysResponse, + ListServiceAccountsRequest, + ListServiceAccountsResponse, + PatchServiceAccountRequest, + Permission, + QueryAuditableServicesRequest, + QueryAuditableServicesResponse, + QueryGrantableRolesRequest, + QueryGrantableRolesResponse, + QueryTestablePermissionsRequest, + QueryTestablePermissionsResponse, + Role, + RoleView, + ServiceAccount, + ServiceAccountKey, + ServiceAccountKeyAlgorithm, + ServiceAccountKeyOrigin, + ServiceAccountPrivateKeyType, + ServiceAccountPublicKeyType, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, + UndeleteRoleRequest, + UndeleteServiceAccountRequest, + UndeleteServiceAccountResponse, + UpdateRoleRequest, + UploadServiceAccountKeyRequest, +) + +__all__ = ( + "AuditData", + "CreateRoleRequest", + "CreateServiceAccountKeyRequest", + "CreateServiceAccountRequest", + "DeleteRoleRequest", + "DeleteServiceAccountKeyRequest", + "DeleteServiceAccountRequest", + "DisableServiceAccountKeyRequest", + "DisableServiceAccountRequest", + "EnableServiceAccountKeyRequest", + "EnableServiceAccountRequest", + "GetRoleRequest", + "GetServiceAccountKeyRequest", + "GetServiceAccountRequest", + "LintPolicyRequest", + "LintPolicyResponse", + "LintResult", + "ListRolesRequest", + "ListRolesResponse", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "PatchServiceAccountRequest", + "Permission", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "Role", + "ServiceAccount", + "ServiceAccountKey", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "UndeleteRoleRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "UpdateRoleRequest", + "UploadServiceAccountKeyRequest", + "RoleView", + "ServiceAccountKeyAlgorithm", + "ServiceAccountKeyOrigin", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/audit_data.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/audit_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d80005294fa9199a48b8f9a649eb40fb8d0cba98 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/audit_data.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.admin.v1", + manifest={ + "AuditData", + }, +) + + +class AuditData(proto.Message): + r"""Audit log information specific to Cloud IAM admin APIs. This message + is serialized as an ``Any`` type in the ``ServiceData`` message of + an ``AuditLog`` message. + + Attributes: + permission_delta (google.cloud.iam_admin_v1.types.AuditData.PermissionDelta): + The permission_delta when when creating or updating a Role. + """ + + class PermissionDelta(proto.Message): + r"""A PermissionDelta message to record the added_permissions and + removed_permissions inside a role. + + Attributes: + added_permissions (MutableSequence[str]): + Added permissions. + removed_permissions (MutableSequence[str]): + Removed permissions. + """ + + added_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + removed_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + permission_delta: PermissionDelta = proto.Field( + proto.MESSAGE, + number=1, + message=PermissionDelta, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/iam.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/iam.py new file mode 100644 index 0000000000000000000000000000000000000000..135de6166498b39c651596a56d0de17115b7ceac --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_admin_v1/types/iam.py @@ -0,0 +1,1902 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.admin.v1", + manifest={ + "ServiceAccountKeyAlgorithm", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", + "ServiceAccountKeyOrigin", + "RoleView", + "ServiceAccount", + "CreateServiceAccountRequest", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "GetServiceAccountRequest", + "DeleteServiceAccountRequest", + "PatchServiceAccountRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "EnableServiceAccountRequest", + "DisableServiceAccountRequest", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "GetServiceAccountKeyRequest", + "ServiceAccountKey", + "CreateServiceAccountKeyRequest", + "UploadServiceAccountKeyRequest", + "DeleteServiceAccountKeyRequest", + "DisableServiceAccountKeyRequest", + "EnableServiceAccountKeyRequest", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "Role", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "ListRolesRequest", + "ListRolesResponse", + "GetRoleRequest", + "CreateRoleRequest", + "UpdateRoleRequest", + "DeleteRoleRequest", + "UndeleteRoleRequest", + "Permission", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "LintPolicyRequest", + "LintResult", + "LintPolicyResponse", + }, +) + + +class ServiceAccountKeyAlgorithm(proto.Enum): + r"""Supported key algorithms. + + Values: + KEY_ALG_UNSPECIFIED (0): + An unspecified key algorithm. + KEY_ALG_RSA_1024 (1): + 1k RSA Key. + KEY_ALG_RSA_2048 (2): + 2k RSA Key. + """ + + KEY_ALG_UNSPECIFIED = 0 + KEY_ALG_RSA_1024 = 1 + KEY_ALG_RSA_2048 = 2 + + +class ServiceAccountPrivateKeyType(proto.Enum): + r"""Supported private key output formats. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified. Equivalent to ``TYPE_GOOGLE_CREDENTIALS_FILE``. + TYPE_PKCS12_FILE (1): + PKCS12 format. The password for the PKCS12 file is + ``notasecret``. For more information, see + https://tools.ietf.org/html/rfc7292. + TYPE_GOOGLE_CREDENTIALS_FILE (2): + Google Credentials File format. + """ + + TYPE_UNSPECIFIED = 0 + TYPE_PKCS12_FILE = 1 + TYPE_GOOGLE_CREDENTIALS_FILE = 2 + + +class ServiceAccountPublicKeyType(proto.Enum): + r"""Supported public key output formats. + + Values: + TYPE_NONE (0): + Do not return the public key. + TYPE_X509_PEM_FILE (1): + X509 PEM format. + TYPE_RAW_PUBLIC_KEY (2): + Raw public key. + """ + + TYPE_NONE = 0 + TYPE_X509_PEM_FILE = 1 + TYPE_RAW_PUBLIC_KEY = 2 + + +class ServiceAccountKeyOrigin(proto.Enum): + r"""Service Account Key Origin. + + Values: + ORIGIN_UNSPECIFIED (0): + Unspecified key origin. + USER_PROVIDED (1): + Key is provided by user. + GOOGLE_PROVIDED (2): + Key is provided by Google. + """ + + ORIGIN_UNSPECIFIED = 0 + USER_PROVIDED = 1 + GOOGLE_PROVIDED = 2 + + +class RoleView(proto.Enum): + r"""A view for Role objects. + + Values: + BASIC (0): + Omits the ``included_permissions`` field. This is the + default value. + FULL (1): + Returns all fields. + """ + + BASIC = 0 + FULL = 1 + + +class ServiceAccount(proto.Message): + r"""An IAM service account. + + A service account is an account for an application or a virtual + machine (VM) instance, not a person. You can use a service account + to call Google APIs. To learn more, read the `overview of service + accounts `__. + + When you create a service account, you specify the project ID that + owns the service account, as well as a name that must be unique + within the project. IAM uses these values to create an email address + that identifies the service account. + + Attributes: + name (str): + The resource name of the service account. + + Use one of the following formats: + + - ``projects/{PROJECT_ID}/serviceAccounts/{EMAIL_ADDRESS}`` + - ``projects/{PROJECT_ID}/serviceAccounts/{UNIQUE_ID}`` + + As an alternative, you can use the ``-`` wildcard character + instead of the project ID: + + - ``projects/-/serviceAccounts/{EMAIL_ADDRESS}`` + - ``projects/-/serviceAccounts/{UNIQUE_ID}`` + + When possible, avoid using the ``-`` wildcard character, + because it can cause response messages to contain misleading + error codes. For example, if you try to get the service + account ``projects/-/serviceAccounts/fake@example.com``, + which does not exist, the response contains an HTTP + ``403 Forbidden`` error instead of a ``404 Not Found`` + error. + project_id (str): + Output only. The ID of the project that owns + the service account. + unique_id (str): + Output only. The unique, stable numeric ID + for the service account. + Each service account retains its unique ID even + if you delete the service account. For example, + if you delete a service account, then create a + new service account with the same name, the new + service account has a different unique ID than + the deleted service account. + email (str): + Output only. The email address of the service + account. + display_name (str): + Optional. A user-specified, human-readable + name for the service account. The maximum length + is 100 UTF-8 bytes. + etag (bytes): + Deprecated. Do not use. + description (str): + Optional. A user-specified, human-readable + description of the service account. The maximum + length is 256 UTF-8 bytes. + oauth2_client_id (str): + Output only. The OAuth 2.0 client ID for the + service account. + disabled (bool): + Output only. Whether the service account is + disabled. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + unique_id: str = proto.Field( + proto.STRING, + number=4, + ) + email: str = proto.Field( + proto.STRING, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=7, + ) + description: str = proto.Field( + proto.STRING, + number=8, + ) + oauth2_client_id: str = proto.Field( + proto.STRING, + number=9, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class CreateServiceAccountRequest(proto.Message): + r"""The service account create request. + + Attributes: + name (str): + Required. The resource name of the project associated with + the service accounts, such as ``projects/my-project-123``. + account_id (str): + Required. The account id that is used to generate the + service account email address and a stable unique id. It is + unique within a project, must be 6-30 characters long, and + match the regular expression ``[a-z]([-a-z0-9]*[a-z0-9])`` + to comply with RFC1035. + service_account (google.cloud.iam_admin_v1.types.ServiceAccount): + The [ServiceAccount][google.iam.admin.v1.ServiceAccount] + resource to create. Currently, only the following values are + user assignable: ``display_name`` and ``description``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account_id: str = proto.Field( + proto.STRING, + number=2, + ) + service_account: "ServiceAccount" = proto.Field( + proto.MESSAGE, + number=3, + message="ServiceAccount", + ) + + +class ListServiceAccountsRequest(proto.Message): + r"""The service account list request. + + Attributes: + name (str): + Required. The resource name of the project associated with + the service accounts, such as ``projects/my-project-123``. + page_size (int): + Optional limit on the number of service accounts to include + in the response. Further accounts can subsequently be + obtained by including the + [ListServiceAccountsResponse.next_page_token][google.iam.admin.v1.ListServiceAccountsResponse.next_page_token] + in a subsequent request. + + The default is 20, and the maximum is 100. + page_token (str): + Optional pagination token returned in an earlier + [ListServiceAccountsResponse.next_page_token][google.iam.admin.v1.ListServiceAccountsResponse.next_page_token]. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServiceAccountsResponse(proto.Message): + r"""The service account list response. + + Attributes: + accounts (MutableSequence[google.cloud.iam_admin_v1.types.ServiceAccount]): + The list of matching service accounts. + next_page_token (str): + To retrieve the next page of results, set + [ListServiceAccountsRequest.page_token][google.iam.admin.v1.ListServiceAccountsRequest.page_token] + to this value. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence["ServiceAccount"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ServiceAccount", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceAccountRequest(proto.Message): + r"""The service account get request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. Using + ``-`` as a wildcard for the ``PROJECT_ID`` will infer the + project from the account. The ``ACCOUNT`` value can be the + ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteServiceAccountRequest(proto.Message): + r"""The service account delete request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. Using + ``-`` as a wildcard for the ``PROJECT_ID`` will infer the + project from the account. The ``ACCOUNT`` value can be the + ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PatchServiceAccountRequest(proto.Message): + r"""The service account patch request. + + You can patch only the ``display_name`` and ``description`` fields. + You must use the ``update_mask`` field to specify which of these + fields you want to patch. + + Only the fields specified in the request are guaranteed to be + returned in the response. Other fields may be empty in the response. + + Attributes: + service_account (google.cloud.iam_admin_v1.types.ServiceAccount): + + update_mask (google.protobuf.field_mask_pb2.FieldMask): + + """ + + service_account: "ServiceAccount" = proto.Field( + proto.MESSAGE, + number=1, + message="ServiceAccount", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UndeleteServiceAccountRequest(proto.Message): + r"""The service account undelete request. + + Attributes: + name (str): + The resource name of the service account in the following + format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT_UNIQUE_ID}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteServiceAccountResponse(proto.Message): + r""" + + Attributes: + restored_account (google.cloud.iam_admin_v1.types.ServiceAccount): + Metadata for the restored service account. + """ + + restored_account: "ServiceAccount" = proto.Field( + proto.MESSAGE, + number=1, + message="ServiceAccount", + ) + + +class EnableServiceAccountRequest(proto.Message): + r"""The service account enable request. + + Attributes: + name (str): + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableServiceAccountRequest(proto.Message): + r"""The service account disable request. + + Attributes: + name (str): + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServiceAccountKeysRequest(proto.Message): + r"""The service account keys list request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID``, will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + key_types (MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]): + Filters the types of keys the user wants to + include in the list response. Duplicate key + types are not allowed. If no key type is + provided, all keys are returned. + """ + + class KeyType(proto.Enum): + r"""``KeyType`` filters to selectively retrieve certain varieties of + keys. + + Values: + KEY_TYPE_UNSPECIFIED (0): + Unspecified key type. The presence of this in + the message will immediately result in an error. + USER_MANAGED (1): + User-managed keys (managed and rotated by the + user). + SYSTEM_MANAGED (2): + System-managed keys (managed and rotated by + Google). + """ + + KEY_TYPE_UNSPECIFIED = 0 + USER_MANAGED = 1 + SYSTEM_MANAGED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + key_types: MutableSequence[KeyType] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=KeyType, + ) + + +class ListServiceAccountKeysResponse(proto.Message): + r"""The service account keys list response. + + Attributes: + keys (MutableSequence[google.cloud.iam_admin_v1.types.ServiceAccountKey]): + The public keys for the service account. + """ + + keys: MutableSequence["ServiceAccountKey"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ServiceAccountKey", + ) + + +class GetServiceAccountKeyRequest(proto.Message): + r"""The service account key get by id request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + public_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType): + Optional. The output format of the public key. The default + is ``TYPE_NONE``, which means that the public key is not + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + public_key_type: "ServiceAccountPublicKeyType" = proto.Field( + proto.ENUM, + number=2, + enum="ServiceAccountPublicKeyType", + ) + + +class ServiceAccountKey(proto.Message): + r"""Represents a service account key. + + A service account has two sets of key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created and deleted by users. + Users are responsible for rotating these keys periodically to + ensure security of their service accounts. Users retain the + private key of these key-pairs, and Google retains ONLY the + public key. + + System-managed keys are automatically rotated by Google, and are + used for signing for a maximum of two weeks. The rotation + process is probabilistic, and usage of the new key will + gradually ramp up and down over the key's lifetime. + + If you cache the public key set for a service account, we + recommend that you update the cache every 15 minutes. + User-managed keys can be added and removed at any time, so it is + important to update the cache frequently. For Google-managed + keys, Google will publish a key at least 6 hours before it is + first used for signing and will keep publishing it for at least + 6 hours after it was last used for signing. + + Public keys for all service accounts are also published at the + OAuth2 Service Account API. + + Attributes: + name (str): + The resource name of the service account key in the + following format + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + private_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType): + The output format for the private key. Only provided in + ``CreateServiceAccountKey`` responses, not in + ``GetServiceAccountKey`` or ``ListServiceAccountKey`` + responses. + + Google never exposes system-managed private keys, and never + retains user-managed private keys. + key_algorithm (google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm): + Specifies the algorithm (and possibly key + size) for the key. + private_key_data (bytes): + The private key data. Only provided in + ``CreateServiceAccountKey`` responses. Make sure to keep the + private key data secure because it allows for the assertion + of the service account identity. When base64 decoded, the + private key data can be used to authenticate with Google API + client libraries and with gcloud auth + activate-service-account. + public_key_data (bytes): + The public key data. Only provided in + ``GetServiceAccountKey`` responses. + valid_after_time (google.protobuf.timestamp_pb2.Timestamp): + The key can be used after this timestamp. + valid_before_time (google.protobuf.timestamp_pb2.Timestamp): + The key can be used before this timestamp. + For system-managed key pairs, this timestamp is + the end time for the private key signing + operation. The public key could still be used + for verification for a few hours after this + time. + key_origin (google.cloud.iam_admin_v1.types.ServiceAccountKeyOrigin): + The key origin. + key_type (google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType): + The key type. + disabled (bool): + The key status. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + private_key_type: "ServiceAccountPrivateKeyType" = proto.Field( + proto.ENUM, + number=2, + enum="ServiceAccountPrivateKeyType", + ) + key_algorithm: "ServiceAccountKeyAlgorithm" = proto.Field( + proto.ENUM, + number=8, + enum="ServiceAccountKeyAlgorithm", + ) + private_key_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + public_key_data: bytes = proto.Field( + proto.BYTES, + number=7, + ) + valid_after_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + valid_before_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + key_origin: "ServiceAccountKeyOrigin" = proto.Field( + proto.ENUM, + number=9, + enum="ServiceAccountKeyOrigin", + ) + key_type: "ListServiceAccountKeysRequest.KeyType" = proto.Field( + proto.ENUM, + number=10, + enum="ListServiceAccountKeysRequest.KeyType", + ) + disabled: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class CreateServiceAccountKeyRequest(proto.Message): + r"""The service account key create request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. Using + ``-`` as a wildcard for the ``PROJECT_ID`` will infer the + project from the account. The ``ACCOUNT`` value can be the + ``email`` address or the ``unique_id`` of the service + account. + private_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType): + The output format of the private key. The default value is + ``TYPE_GOOGLE_CREDENTIALS_FILE``, which is the Google + Credentials File format. + key_algorithm (google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm): + Which type of key and algorithm to use for + the key. The default is currently a 2K RSA key. + However this may change in the future. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + private_key_type: "ServiceAccountPrivateKeyType" = proto.Field( + proto.ENUM, + number=2, + enum="ServiceAccountPrivateKeyType", + ) + key_algorithm: "ServiceAccountKeyAlgorithm" = proto.Field( + proto.ENUM, + number=3, + enum="ServiceAccountKeyAlgorithm", + ) + + +class UploadServiceAccountKeyRequest(proto.Message): + r"""The service account key upload request. + + Attributes: + name (str): + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + public_key_data (bytes): + The public key to associate with the service account. Must + be an RSA public key that is wrapped in an X.509 v3 + certificate. Include the first line, + ``-----BEGIN CERTIFICATE-----``, and the last line, + ``-----END CERTIFICATE-----``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + public_key_data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class DeleteServiceAccountKeyRequest(proto.Message): + r"""The service account key delete request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableServiceAccountKeyRequest(proto.Message): + r"""The service account key disable request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EnableServiceAccountKeyRequest(proto.Message): + r"""The service account key enable request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SignBlobRequest(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob request. + + Attributes: + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + bytes_to_sign (bytes): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The bytes to sign. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + bytes_to_sign: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class SignBlobResponse(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob response. + + Attributes: + key_id (str): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The id of the key used to sign the blob. + signature (bytes): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The signed blob. + """ + + key_id: str = proto.Field( + proto.STRING, + number=1, + ) + signature: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class SignJwtRequest(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT request. + + Attributes: + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + payload (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The JWT payload to sign. Must be a serialized JSON object + that contains a JWT Claims Set. For example: + ``{"sub": "user@example.com", "iat": 313435}`` + + If the JWT Claims Set contains an expiration time (``exp``) + claim, it must be an integer timestamp that is not in the + past and no more than 12 hours in the future. + + If the JWT Claims Set does not contain an expiration time + (``exp``) claim, this claim is added automatically, with a + timestamp that is 1 hour in the future. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + payload: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SignJwtResponse(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT response. + + Attributes: + key_id (str): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The id of the key used to sign the JWT. + signed_jwt (str): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The signed JWT. + """ + + key_id: str = proto.Field( + proto.STRING, + number=1, + ) + signed_jwt: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Role(proto.Message): + r"""A role in the Identity and Access Management API. + + Attributes: + name (str): + The name of the role. + + When Role is used in CreateRole, the role name must not be + set. + + When Role is used in output and other input such as + UpdateRole, the role name is the complete path, e.g., + roles/logging.viewer for predefined roles and + organizations/{ORGANIZATION_ID}/roles/logging.viewer for + custom roles. + title (str): + Optional. A human-readable title for the + role. Typically this is limited to 100 UTF-8 + bytes. + description (str): + Optional. A human-readable description for + the role. + included_permissions (MutableSequence[str]): + The names of the permissions this role grants + when bound in an IAM policy. + stage (google.cloud.iam_admin_v1.types.Role.RoleLaunchStage): + The current launch stage of the role. If the ``ALPHA`` + launch stage has been selected for a role, the ``stage`` + field will not be included in the returned definition for + the role. + etag (bytes): + Used to perform a consistent + read-modify-write. + deleted (bool): + The current deleted state of the role. This + field is read only. It will be ignored in calls + to CreateRole and UpdateRole. + """ + + class RoleLaunchStage(proto.Enum): + r"""A stage representing a role's lifecycle phase. + + Values: + ALPHA (0): + The user has indicated this role is currently in an Alpha + phase. If this launch stage is selected, the ``stage`` field + will not be included when requesting the definition for a + given role. + BETA (1): + The user has indicated this role is currently + in a Beta phase. + GA (2): + The user has indicated this role is generally + available. + DEPRECATED (4): + The user has indicated this role is being + deprecated. + DISABLED (5): + This role is disabled and will not contribute + permissions to any principals it is granted to + in policies. + EAP (6): + The user has indicated this role is currently + in an EAP phase. + """ + + ALPHA = 0 + BETA = 1 + GA = 2 + DEPRECATED = 4 + DISABLED = 5 + EAP = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + included_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + stage: RoleLaunchStage = proto.Field( + proto.ENUM, + number=8, + enum=RoleLaunchStage, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=9, + ) + deleted: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class QueryGrantableRolesRequest(proto.Message): + r"""The grantable role query request. + + Attributes: + full_resource_name (str): + Required. The full resource name to query from the list of + grantable roles. + + The name follows the Google Cloud Platform resource format. + For example, a Cloud Platform project with id ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + view (google.cloud.iam_admin_v1.types.RoleView): + + page_size (int): + Optional limit on the number of roles to + include in the response. + The default is 300, and the maximum is 1,000. + page_token (str): + Optional pagination token returned in an + earlier QueryGrantableRolesResponse. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "RoleView" = proto.Field( + proto.ENUM, + number=2, + enum="RoleView", + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class QueryGrantableRolesResponse(proto.Message): + r"""The grantable role query response. + + Attributes: + roles (MutableSequence[google.cloud.iam_admin_v1.types.Role]): + The list of matching roles. + next_page_token (str): + To retrieve the next page of results, set + ``QueryGrantableRolesRequest.page_token`` to this value. + """ + + @property + def raw_page(self): + return self + + roles: MutableSequence["Role"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Role", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListRolesRequest(proto.Message): + r"""The request to get all roles defined under a resource. + + Attributes: + parent (str): + The ``parent`` parameter's value depends on the target + resource for the request, namely + ```roles`` `__, + ```projects`` `__, + or + ```organizations`` `__. + Each resource type's ``parent`` value format is described + below: + + - ```roles.list()`` `__: + An empty string. This method doesn't require a resource; + it simply returns all `predefined + roles `__ + in Cloud IAM. Example request URL: + ``https://iam.googleapis.com/v1/roles`` + + - ```projects.roles.list()`` `__: + ``projects/{PROJECT_ID}``. This method lists all + project-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles`` + + - ```organizations.roles.list()`` `__: + ``organizations/{ORGANIZATION_ID}``. This method lists all + organization-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles`` + + Note: Wildcard (\*) values are invalid; you must specify a + complete project ID or organization ID. + page_size (int): + Optional limit on the number of roles to + include in the response. + The default is 300, and the maximum is 1,000. + page_token (str): + Optional pagination token returned in an + earlier ListRolesResponse. + view (google.cloud.iam_admin_v1.types.RoleView): + Optional view for the returned Role objects. When ``FULL`` + is specified, the ``includedPermissions`` field is returned, + which includes a list of all permissions in the role. The + default value is ``BASIC``, which does not return the + ``includedPermissions`` field. + show_deleted (bool): + Include Roles that have been deleted. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + view: "RoleView" = proto.Field( + proto.ENUM, + number=4, + enum="RoleView", + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListRolesResponse(proto.Message): + r"""The response containing the roles defined under a resource. + + Attributes: + roles (MutableSequence[google.cloud.iam_admin_v1.types.Role]): + The Roles defined on this resource. + next_page_token (str): + To retrieve the next page of results, set + ``ListRolesRequest.page_token`` to this value. + """ + + @property + def raw_page(self): + return self + + roles: MutableSequence["Role"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Role", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetRoleRequest(proto.Message): + r"""The request to get the definition of an existing role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```roles`` `__, + ```projects`` `__, + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```roles.get()`` `__: + ``roles/{ROLE_NAME}``. This method returns results from + all `predefined + roles `__ + in Cloud IAM. Example request URL: + ``https://iam.googleapis.com/v1/roles/{ROLE_NAME}`` + + - ```projects.roles.get()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method returns only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.get()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method returns only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (\*) values are invalid; you must specify a + complete project ID or organization ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateRoleRequest(proto.Message): + r"""The request to create a new role. + + Attributes: + parent (str): + The ``parent`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``parent`` value format is described + below: + + - ```projects.roles.create()`` `__: + ``projects/{PROJECT_ID}``. This method creates + project-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles`` + + - ```organizations.roles.create()`` `__: + ``organizations/{ORGANIZATION_ID}``. This method creates + organization-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles`` + + Note: Wildcard (\*) values are invalid; you must specify a + complete project ID or organization ID. + role_id (str): + The role ID to use for this role. + + A role ID may contain alphanumeric characters, underscores + (``_``), and periods (``.``). It must contain a minimum of 3 + characters and a maximum of 64 characters. + role (google.cloud.iam_admin_v1.types.Role): + The Role resource to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + role_id: str = proto.Field( + proto.STRING, + number=2, + ) + role: "Role" = proto.Field( + proto.MESSAGE, + number=3, + message="Role", + ) + + +class UpdateRoleRequest(proto.Message): + r"""The request to update a role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```projects.roles.patch()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method updates only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.patch()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method updates only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (\*) values are invalid; you must specify a + complete project ID or organization ID. + role (google.cloud.iam_admin_v1.types.Role): + The updated role. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + A mask describing which fields in the Role + have changed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + role: "Role" = proto.Field( + proto.MESSAGE, + number=2, + message="Role", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteRoleRequest(proto.Message): + r"""The request to delete an existing role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```projects.roles.delete()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method deletes only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.delete()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method deletes only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (\*) values are invalid; you must specify a + complete project ID or organization ID. + etag (bytes): + Used to perform a consistent + read-modify-write. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class UndeleteRoleRequest(proto.Message): + r"""The request to undelete an existing role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```projects.roles.undelete()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method undeletes only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.undelete()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method undeletes only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (\*) values are invalid; you must specify a + complete project ID or organization ID. + etag (bytes): + Used to perform a consistent + read-modify-write. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class Permission(proto.Message): + r"""A permission which can be included by a role. + + Attributes: + name (str): + The name of this Permission. + title (str): + The title of this Permission. + description (str): + A brief description of what this Permission + is used for. This permission can ONLY be used in + predefined roles. + only_in_predefined_roles (bool): + + stage (google.cloud.iam_admin_v1.types.Permission.PermissionLaunchStage): + The current launch stage of the permission. + custom_roles_support_level (google.cloud.iam_admin_v1.types.Permission.CustomRolesSupportLevel): + The current custom role support level. + api_disabled (bool): + The service API associated with the + permission is not enabled. + primary_permission (str): + The preferred name for this permission. If present, then + this permission is an alias of, and equivalent to, the + listed primary_permission. + """ + + class PermissionLaunchStage(proto.Enum): + r"""A stage representing a permission's lifecycle phase. + + Values: + ALPHA (0): + The permission is currently in an alpha + phase. + BETA (1): + The permission is currently in a beta phase. + GA (2): + The permission is generally available. + DEPRECATED (3): + The permission is being deprecated. + """ + + ALPHA = 0 + BETA = 1 + GA = 2 + DEPRECATED = 3 + + class CustomRolesSupportLevel(proto.Enum): + r"""The state of the permission with regards to custom roles. + + Values: + SUPPORTED (0): + Default state. Permission is fully supported + for custom role use. + TESTING (1): + Permission is being tested to check custom + role compatibility. + NOT_SUPPORTED (2): + Permission is not supported for custom role + use. + """ + + SUPPORTED = 0 + TESTING = 1 + NOT_SUPPORTED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + only_in_predefined_roles: bool = proto.Field( + proto.BOOL, + number=4, + ) + stage: PermissionLaunchStage = proto.Field( + proto.ENUM, + number=5, + enum=PermissionLaunchStage, + ) + custom_roles_support_level: CustomRolesSupportLevel = proto.Field( + proto.ENUM, + number=6, + enum=CustomRolesSupportLevel, + ) + api_disabled: bool = proto.Field( + proto.BOOL, + number=7, + ) + primary_permission: str = proto.Field( + proto.STRING, + number=8, + ) + + +class QueryTestablePermissionsRequest(proto.Message): + r"""A request to get permissions which can be tested on a + resource. + + Attributes: + full_resource_name (str): + Required. The full resource name to query from the list of + testable permissions. + + The name follows the Google Cloud Platform resource format. + For example, a Cloud Platform project with id ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + page_size (int): + Optional limit on the number of permissions + to include in the response. + The default is 100, and the maximum is 1,000. + page_token (str): + Optional pagination token returned in an + earlier QueryTestablePermissionsRequest. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class QueryTestablePermissionsResponse(proto.Message): + r"""The response containing permissions which can be tested on a + resource. + + Attributes: + permissions (MutableSequence[google.cloud.iam_admin_v1.types.Permission]): + The Permissions testable on the requested + resource. + next_page_token (str): + To retrieve the next page of results, set + ``QueryTestableRolesRequest.page_token`` to this value. + """ + + @property + def raw_page(self): + return self + + permissions: MutableSequence["Permission"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Permission", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class QueryAuditableServicesRequest(proto.Message): + r"""A request to get the list of auditable services for a + resource. + + Attributes: + full_resource_name (str): + Required. The full resource name to query from the list of + auditable services. + + The name follows the Google Cloud Platform resource format. + For example, a Cloud Platform project with id ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class QueryAuditableServicesResponse(proto.Message): + r"""A response containing a list of auditable services for a + resource. + + Attributes: + services (MutableSequence[google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse.AuditableService]): + The auditable services for a resource. + """ + + class AuditableService(proto.Message): + r"""Contains information about an auditable service. + + Attributes: + name (str): + Public name of the service. + For example, the service name for Cloud IAM is + 'iam.googleapis.com'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + services: MutableSequence[AuditableService] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AuditableService, + ) + + +class LintPolicyRequest(proto.Message): + r"""The request to lint a Cloud IAM policy object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + full_resource_name (str): + The full resource name of the policy this lint request is + about. + + The name follows the Google Cloud Platform (GCP) resource + format. For example, a GCP project with ID ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + + The resource name is not used to read the policy instance + from the Cloud IAM database. The candidate policy for lint + has to be provided in the same request object. + condition (google.type.expr_pb2.Expr): + [google.iam.v1.Binding.condition] + [google.iam.v1.Binding.condition] object to be linted. + + This field is a member of `oneof`_ ``lint_object``. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=5, + oneof="lint_object", + message=expr_pb2.Expr, + ) + + +class LintResult(proto.Message): + r"""Structured response of a single validation unit. + + Attributes: + level (google.cloud.iam_admin_v1.types.LintResult.Level): + The validation unit level. + validation_unit_name (str): + The validation unit name, for instance + "lintValidationUnits/ConditionComplexityCheck". + severity (google.cloud.iam_admin_v1.types.LintResult.Severity): + The validation unit severity. + field_name (str): + The name of the field for which this lint result is about. + + For nested messages ``field_name`` consists of names of the + embedded fields separated by period character. The top-level + qualifier is the input object to lint in the request. For + example, the ``field_name`` value ``condition.expression`` + identifies a lint result for the ``expression`` field of the + provided condition. + location_offset (int): + 0-based character position of problematic construct within + the object identified by ``field_name``. Currently, this is + populated only for condition expression. + debug_message (str): + Human readable debug message associated with + the issue. + """ + + class Level(proto.Enum): + r"""Possible Level values of a validation unit corresponding to + its domain of discourse. + + Values: + LEVEL_UNSPECIFIED (0): + Level is unspecified. + CONDITION (3): + A validation unit which operates on an + individual condition within a binding. + """ + + LEVEL_UNSPECIFIED = 0 + CONDITION = 3 + + class Severity(proto.Enum): + r"""Possible Severity values of an issued result. + + Values: + SEVERITY_UNSPECIFIED (0): + Severity is unspecified. + ERROR (1): + A validation unit returns an error only for critical issues. + If an attempt is made to set the problematic policy without + rectifying the critical issue, it causes the ``setPolicy`` + operation to fail. + WARNING (2): + Any issue which is severe enough but does not cause an + error. For example, suspicious constructs in the input + object will not necessarily fail ``setPolicy``, but there is + a high likelihood that they won't behave as expected during + policy evaluation in ``checkPolicy``. This includes the + following common scenarios: + + - Unsatisfiable condition: Expired timestamp in date/time + condition. + - Ineffective condition: Condition on a + pair which is granted unconditionally in another binding + of the same policy. + NOTICE (3): + Reserved for the issues that are not severe as + ``ERROR``/``WARNING``, but need special handling. For + instance, messages about skipped validation units are issued + as ``NOTICE``. + INFO (4): + Any informative statement which is not severe enough to + raise ``ERROR``/``WARNING``/``NOTICE``, like auto-correction + recommendations on the input content. Note that current + version of the linter does not utilize ``INFO``. + DEPRECATED (5): + Deprecated severity level. + """ + + SEVERITY_UNSPECIFIED = 0 + ERROR = 1 + WARNING = 2 + NOTICE = 3 + INFO = 4 + DEPRECATED = 5 + + level: Level = proto.Field( + proto.ENUM, + number=1, + enum=Level, + ) + validation_unit_name: str = proto.Field( + proto.STRING, + number=2, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=3, + enum=Severity, + ) + field_name: str = proto.Field( + proto.STRING, + number=5, + ) + location_offset: int = proto.Field( + proto.INT32, + number=6, + ) + debug_message: str = proto.Field( + proto.STRING, + number=7, + ) + + +class LintPolicyResponse(proto.Message): + r"""The response of a lint operation. An empty response indicates + the operation was able to fully execute and no lint issue was + found. + + Attributes: + lint_results (MutableSequence[google.cloud.iam_admin_v1.types.LintResult]): + List of lint results sorted by ``severity`` in descending + order. + """ + + lint_results: MutableSequence["LintResult"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LintResult", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed35bf157aea7a1a4d938839d73763f24f42a0e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/__init__.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.iam_credentials import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.iam_credentials_v1.services.iam_credentials.async_client import ( + IAMCredentialsAsyncClient, +) +from google.cloud.iam_credentials_v1.services.iam_credentials.client import ( + IAMCredentialsClient, +) +from google.cloud.iam_credentials_v1.types.common import ( + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GenerateIdTokenRequest, + GenerateIdTokenResponse, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, +) + +__all__ = ( + "IAMCredentialsClient", + "IAMCredentialsAsyncClient", + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8a079136b54dd1b5a354a9a0be5c5fb174d0b7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/__init__.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.iam_credentials_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.iam_credentials import IAMCredentialsAsyncClient, IAMCredentialsClient +from .types.common import ( + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GenerateIdTokenRequest, + GenerateIdTokenResponse, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.iam_credentials_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.iam_credentials_v1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.iam_credentials_v1" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "IAMCredentialsAsyncClient", + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "IAMCredentialsClient", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..47932c33b0d58d0d45aa1c057e485f0c34f06eda --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/gapic_metadata.json @@ -0,0 +1,88 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_credentials_v1", + "protoPackage": "google.iam.credentials.v1", + "schema": "1.0", + "services": { + "IAMCredentials": { + "clients": { + "grpc": { + "libraryClient": "IAMCredentialsClient", + "rpcs": { + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GenerateIdToken": { + "methods": [ + "generate_id_token" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IAMCredentialsAsyncClient", + "rpcs": { + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GenerateIdToken": { + "methods": [ + "generate_id_token" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + } + } + }, + "rest": { + "libraryClient": "IAMCredentialsClient", + "rpcs": { + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GenerateIdToken": { + "methods": [ + "generate_id_token" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36b57fe4c55513a84715808f4500244daf5e9842 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import IAMCredentialsAsyncClient +from .client import IAMCredentialsClient + +__all__ = ( + "IAMCredentialsClient", + "IAMCredentialsAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..cfd5a7b2dce6dbe3bf7273566421227195356e1f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py @@ -0,0 +1,932 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_credentials_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.iam_credentials_v1.types import common + +from .client import IAMCredentialsClient +from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class IAMCredentialsAsyncClient: + """A service account is a special type of Google account that + belongs to your application or a virtual machine (VM), instead + of to an individual end user. Your application assumes the + identity of the service account to call Google APIs, so that the + users aren't directly involved. + + Service account credentials are used to temporarily assume the + identity of the service account. Supported credential types + include OAuth 2.0 access tokens, OpenID Connect ID tokens, + self-signed JSON Web Tokens (JWTs), and more. + """ + + _client: IAMCredentialsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = IAMCredentialsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = IAMCredentialsClient._DEFAULT_UNIVERSE + + service_account_path = staticmethod(IAMCredentialsClient.service_account_path) + parse_service_account_path = staticmethod( + IAMCredentialsClient.parse_service_account_path + ) + common_billing_account_path = staticmethod( + IAMCredentialsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + IAMCredentialsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path) + parse_common_folder_path = staticmethod( + IAMCredentialsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + IAMCredentialsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + IAMCredentialsClient.parse_common_organization_path + ) + common_project_path = staticmethod(IAMCredentialsClient.common_project_path) + parse_common_project_path = staticmethod( + IAMCredentialsClient.parse_common_project_path + ) + common_location_path = staticmethod(IAMCredentialsClient.common_location_path) + parse_common_location_path = staticmethod( + IAMCredentialsClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMCredentialsAsyncClient: The constructed client. + """ + sa_info_func = ( + IAMCredentialsClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(IAMCredentialsAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMCredentialsAsyncClient: The constructed client. + """ + sa_file_func = ( + IAMCredentialsClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(IAMCredentialsAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return IAMCredentialsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> IAMCredentialsTransport: + """Returns the transport used by the client instance. + + Returns: + IAMCredentialsTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = IAMCredentialsClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the iam credentials async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,IAMCredentialsTransport,Callable[..., IAMCredentialsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the IAMCredentialsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = IAMCredentialsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam.credentials_v1.IAMCredentialsAsyncClient`.", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "credentialsType": None, + }, + ) + + async def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: + r"""Generates an OAuth 2.0 access token for a service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + async def sample_generate_access_token(): + # Create a client + client = iam_credentials_v1.IAMCredentialsAsyncClient() + + # Initialize request argument(s) + request = iam_credentials_v1.GenerateAccessTokenRequest( + name="name_value", + scope=['scope_value1', 'scope_value2'], + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_credentials_v1.types.GenerateAccessTokenRequest, dict]]): + The request object. + name (:class:`str`): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (:class:`MutableSequence[str]`): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope (:class:`MutableSequence[str]`): + Required. Code to identify the scopes + to be included in the OAuth 2.0 access + token. See + https://developers.google.com/identity/protocols/googlescopes + for more information. + At least one value required. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lifetime (:class:`google.protobuf.duration_pb2.Duration`): + The desired lifetime duration of the + access token in seconds. Must be set to + a value less than or equal to 3600 (1 + hour). If a value is not specified, the + token's lifetime will be set to a + default value of one hour. + + This corresponds to the ``lifetime`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, scope, lifetime] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.GenerateAccessTokenRequest): + request = common.GenerateAccessTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if lifetime is not None: + request.lifetime = lifetime + if delegates: + request.delegates.extend(delegates) + if scope: + request.scope.extend(scope) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_access_token + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: + r"""Generates an OpenID Connect ID token for a service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + async def sample_generate_id_token(): + # Create a client + client = iam_credentials_v1.IAMCredentialsAsyncClient() + + # Initialize request argument(s) + request = iam_credentials_v1.GenerateIdTokenRequest( + name="name_value", + audience="audience_value", + ) + + # Make the request + response = await client.generate_id_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_credentials_v1.types.GenerateIdTokenRequest, dict]]): + The request object. + name (:class:`str`): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (:class:`MutableSequence[str]`): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audience (:class:`str`): + Required. The audience for the token, + such as the API or account that this + token grants access to. + + This corresponds to the ``audience`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + include_email (:class:`bool`): + Include the service account email in the token. If set + to ``true``, the token will contain ``email`` and + ``email_verified`` claims. + + This corresponds to the ``include_email`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, audience, include_email] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.GenerateIdTokenRequest): + request = common.GenerateIdTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if audience is not None: + request.audience = audience + if include_email is not None: + request.include_email = include_email + if delegates: + request.delegates.extend(delegates) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_id_token + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: + r"""Signs a blob using a service account's system-managed + private key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + async def sample_sign_blob(): + # Create a client + client = iam_credentials_v1.IAMCredentialsAsyncClient() + + # Initialize request argument(s) + request = iam_credentials_v1.SignBlobRequest( + name="name_value", + payload=b'payload_blob', + ) + + # Make the request + response = await client.sign_blob(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_credentials_v1.types.SignBlobRequest, dict]]): + The request object. + name (:class:`str`): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (:class:`MutableSequence[str]`): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`bytes`): + Required. The bytes to sign. + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.SignBlobResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, payload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.SignBlobRequest): + request = common.SignBlobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if payload is not None: + request.payload = payload + if delegates: + request.delegates.extend(delegates) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.sign_blob + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: + r"""Signs a JWT using a service account's system-managed + private key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + async def sample_sign_jwt(): + # Create a client + client = iam_credentials_v1.IAMCredentialsAsyncClient() + + # Initialize request argument(s) + request = iam_credentials_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = await client.sign_jwt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_credentials_v1.types.SignJwtRequest, dict]]): + The request object. + name (:class:`str`): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (:class:`MutableSequence[str]`): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`str`): + Required. The JWT payload to sign: a + JSON object that contains a JWT Claims + Set. + + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.SignJwtResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, payload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.SignJwtRequest): + request = common.SignJwtRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if payload is not None: + request.payload = payload + if delegates: + request.delegates.extend(delegates) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.sign_jwt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "IAMCredentialsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("IAMCredentialsAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/client.py new file mode 100644 index 0000000000000000000000000000000000000000..db33e92d2c1d2ee5ba414ce70dc353cff5b9068c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/client.py @@ -0,0 +1,1358 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_credentials_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.iam_credentials_v1.types import common + +from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .transports.grpc import IAMCredentialsGrpcTransport +from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport +from .transports.rest import IAMCredentialsRestTransport + + +class IAMCredentialsClientMeta(type): + """Metaclass for the IAMCredentials client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] + _transport_registry["grpc"] = IAMCredentialsGrpcTransport + _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport + _transport_registry["rest"] = IAMCredentialsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[IAMCredentialsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class IAMCredentialsClient(metaclass=IAMCredentialsClientMeta): + """A service account is a special type of Google account that + belongs to your application or a virtual machine (VM), instead + of to an individual end user. Your application assumes the + identity of the service account to call Google APIs, so that the + users aren't directly involved. + + Service account credentials are used to temporarily assume the + identity of the service account. Supported credential types + include OAuth 2.0 access tokens, OpenID Connect ID tokens, + self-signed JSON Web Tokens (JWTs), and more. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iamcredentials.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iamcredentials.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMCredentialsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMCredentialsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> IAMCredentialsTransport: + """Returns the transport used by the client instance. + + Returns: + IAMCredentialsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def service_account_path( + project: str, + service_account: str, + ) -> str: + """Returns a fully-qualified service_account string.""" + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + + @staticmethod + def parse_service_account_path(path: str) -> Dict[str, str]: + """Parses a service_account path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = IAMCredentialsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = IAMCredentialsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = IAMCredentialsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the iam credentials client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,IAMCredentialsTransport,Callable[..., IAMCredentialsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the IAMCredentialsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + IAMCredentialsClient._read_environment_variables() + ) + self._client_cert_source = IAMCredentialsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = IAMCredentialsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, IAMCredentialsTransport) + if transport_provided: + # transport is a IAMCredentialsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(IAMCredentialsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or IAMCredentialsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] + ] = ( + IAMCredentialsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., IAMCredentialsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "credentialsType": None, + }, + ) + + def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: + r"""Generates an OAuth 2.0 access token for a service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + def sample_generate_access_token(): + # Create a client + client = iam_credentials_v1.IAMCredentialsClient() + + # Initialize request argument(s) + request = iam_credentials_v1.GenerateAccessTokenRequest( + name="name_value", + scope=['scope_value1', 'scope_value2'], + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_credentials_v1.types.GenerateAccessTokenRequest, dict]): + The request object. + name (str): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope (MutableSequence[str]): + Required. Code to identify the scopes + to be included in the OAuth 2.0 access + token. See + https://developers.google.com/identity/protocols/googlescopes + for more information. + At least one value required. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lifetime (google.protobuf.duration_pb2.Duration): + The desired lifetime duration of the + access token in seconds. Must be set to + a value less than or equal to 3600 (1 + hour). If a value is not specified, the + token's lifetime will be set to a + default value of one hour. + + This corresponds to the ``lifetime`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, scope, lifetime] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.GenerateAccessTokenRequest): + request = common.GenerateAccessTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if delegates is not None: + request.delegates = delegates + if scope is not None: + request.scope = scope + if lifetime is not None: + request.lifetime = lifetime + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: + r"""Generates an OpenID Connect ID token for a service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + def sample_generate_id_token(): + # Create a client + client = iam_credentials_v1.IAMCredentialsClient() + + # Initialize request argument(s) + request = iam_credentials_v1.GenerateIdTokenRequest( + name="name_value", + audience="audience_value", + ) + + # Make the request + response = client.generate_id_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_credentials_v1.types.GenerateIdTokenRequest, dict]): + The request object. + name (str): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audience (str): + Required. The audience for the token, + such as the API or account that this + token grants access to. + + This corresponds to the ``audience`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + include_email (bool): + Include the service account email in the token. If set + to ``true``, the token will contain ``email`` and + ``email_verified`` claims. + + This corresponds to the ``include_email`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, audience, include_email] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.GenerateIdTokenRequest): + request = common.GenerateIdTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if delegates is not None: + request.delegates = delegates + if audience is not None: + request.audience = audience + if include_email is not None: + request.include_email = include_email + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_id_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: + r"""Signs a blob using a service account's system-managed + private key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + def sample_sign_blob(): + # Create a client + client = iam_credentials_v1.IAMCredentialsClient() + + # Initialize request argument(s) + request = iam_credentials_v1.SignBlobRequest( + name="name_value", + payload=b'payload_blob', + ) + + # Make the request + response = client.sign_blob(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_credentials_v1.types.SignBlobRequest, dict]): + The request object. + name (str): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (bytes): + Required. The bytes to sign. + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.SignBlobResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, payload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.SignBlobRequest): + request = common.SignBlobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if delegates is not None: + request.delegates = delegates + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.sign_blob] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: + r"""Signs a JWT using a service account's system-managed + private key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_credentials_v1 + + def sample_sign_jwt(): + # Create a client + client = iam_credentials_v1.IAMCredentialsClient() + + # Initialize request argument(s) + request = iam_credentials_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = client.sign_jwt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_credentials_v1.types.SignJwtRequest, dict]): + The request object. + name (str): + Required. The resource name of the service account for + which the credentials are requested, in the following + format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. + Each service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its + next service account in the chain. The last service + account in the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the + service account that is specified in the ``name`` field + of the request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it + with a project ID is invalid. + + This corresponds to the ``delegates`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (str): + Required. The JWT payload to sign: a + JSON object that contains a JWT Claims + Set. + + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_credentials_v1.types.SignJwtResponse: + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, delegates, payload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, common.SignJwtRequest): + request = common.SignJwtRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if delegates is not None: + request.delegates = delegates + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.sign_jwt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "IAMCredentialsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("IAMCredentialsClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..897cc6ef3890431b68a10de79dbbde11c46670f8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import IAMCredentialsTransport +from .grpc import IAMCredentialsGrpcTransport +from .grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport +from .rest import IAMCredentialsRestInterceptor, IAMCredentialsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] +_transport_registry["grpc"] = IAMCredentialsGrpcTransport +_transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport +_transport_registry["rest"] = IAMCredentialsRestTransport + +__all__ = ( + "IAMCredentialsTransport", + "IAMCredentialsGrpcTransport", + "IAMCredentialsGrpcAsyncIOTransport", + "IAMCredentialsRestTransport", + "IAMCredentialsRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..9eaf10c10ffe622d4f1a648f327af72b20075435 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_credentials_v1 import gapic_version as package_version +from google.cloud.iam_credentials_v1.types import common + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class IAMCredentialsTransport(abc.ABC): + """Abstract transport class for IAMCredentials.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iamcredentials.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.generate_access_token: gapic_v1.method.wrap_method( + self.generate_access_token, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_id_token: gapic_v1.method.wrap_method( + self.generate_id_token, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.sign_blob: gapic_v1.method.wrap_method( + self.sign_blob, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.sign_jwt: gapic_v1.method.wrap_method( + self.sign_jwt, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], + Union[ + common.GenerateAccessTokenResponse, + Awaitable[common.GenerateAccessTokenResponse], + ], + ]: + raise NotImplementedError() + + @property + def generate_id_token( + self, + ) -> Callable[ + [common.GenerateIdTokenRequest], + Union[ + common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] + ], + ]: + raise NotImplementedError() + + @property + def sign_blob( + self, + ) -> Callable[ + [common.SignBlobRequest], + Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], + ]: + raise NotImplementedError() + + @property + def sign_jwt( + self, + ) -> Callable[ + [common.SignJwtRequest], + Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("IAMCredentialsTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..538ea7436ff87c1d60093e77ae8cb1a328f301fc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py @@ -0,0 +1,451 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_credentials_v1.types import common + +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class IAMCredentialsGrpcTransport(IAMCredentialsTransport): + """gRPC backend transport for IAMCredentials. + + A service account is a special type of Google account that + belongs to your application or a virtual machine (VM), instead + of to an individual end user. Your application assumes the + identity of the service account to call Google APIs, so that the + users aren't directly involved. + + Service account credentials are used to temporarily assume the + identity of the service account. Supported credential types + include OAuth 2.0 access tokens, OpenID Connect ID tokens, + self-signed JSON Web Tokens (JWTs), and more. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: + r"""Return a callable for the generate access token method over gRPC. + + Generates an OAuth 2.0 access token for a service + account. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + ~.GenerateAccessTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_access_token" not in self._stubs: + self._stubs["generate_access_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", + request_serializer=common.GenerateAccessTokenRequest.serialize, + response_deserializer=common.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs["generate_access_token"] + + @property + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: + r"""Return a callable for the generate id token method over gRPC. + + Generates an OpenID Connect ID token for a service + account. + + Returns: + Callable[[~.GenerateIdTokenRequest], + ~.GenerateIdTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_id_token" not in self._stubs: + self._stubs["generate_id_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", + request_serializer=common.GenerateIdTokenRequest.serialize, + response_deserializer=common.GenerateIdTokenResponse.deserialize, + ) + return self._stubs["generate_id_token"] + + @property + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: + r"""Return a callable for the sign blob method over gRPC. + + Signs a blob using a service account's system-managed + private key. + + Returns: + Callable[[~.SignBlobRequest], + ~.SignBlobResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignBlob", + request_serializer=common.SignBlobRequest.serialize, + response_deserializer=common.SignBlobResponse.deserialize, + ) + return self._stubs["sign_blob"] + + @property + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: + r"""Return a callable for the sign jwt method over gRPC. + + Signs a JWT using a service account's system-managed + private key. + + Returns: + Callable[[~.SignJwtRequest], + ~.SignJwtResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignJwt", + request_serializer=common.SignJwtRequest.serialize, + response_deserializer=common.SignJwtResponse.deserialize, + ) + return self._stubs["sign_jwt"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("IAMCredentialsGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..97da99bf009a8cb8fa944a3cb4afe76f70bc7b87 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_credentials_v1.types import common + +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .grpc import IAMCredentialsGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class IAMCredentialsGrpcAsyncIOTransport(IAMCredentialsTransport): + """gRPC AsyncIO backend transport for IAMCredentials. + + A service account is a special type of Google account that + belongs to your application or a virtual machine (VM), instead + of to an individual end user. Your application assumes the + identity of the service account to call Google APIs, so that the + users aren't directly involved. + + Service account credentials are used to temporarily assume the + identity of the service account. Supported credential types + include OAuth 2.0 access tokens, OpenID Connect ID tokens, + self-signed JSON Web Tokens (JWTs), and more. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], + Awaitable[common.GenerateAccessTokenResponse], + ]: + r"""Return a callable for the generate access token method over gRPC. + + Generates an OAuth 2.0 access token for a service + account. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + Awaitable[~.GenerateAccessTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_access_token" not in self._stubs: + self._stubs["generate_access_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", + request_serializer=common.GenerateAccessTokenRequest.serialize, + response_deserializer=common.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs["generate_access_token"] + + @property + def generate_id_token( + self, + ) -> Callable[ + [common.GenerateIdTokenRequest], Awaitable[common.GenerateIdTokenResponse] + ]: + r"""Return a callable for the generate id token method over gRPC. + + Generates an OpenID Connect ID token for a service + account. + + Returns: + Callable[[~.GenerateIdTokenRequest], + Awaitable[~.GenerateIdTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_id_token" not in self._stubs: + self._stubs["generate_id_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", + request_serializer=common.GenerateIdTokenRequest.serialize, + response_deserializer=common.GenerateIdTokenResponse.deserialize, + ) + return self._stubs["generate_id_token"] + + @property + def sign_blob( + self, + ) -> Callable[[common.SignBlobRequest], Awaitable[common.SignBlobResponse]]: + r"""Return a callable for the sign blob method over gRPC. + + Signs a blob using a service account's system-managed + private key. + + Returns: + Callable[[~.SignBlobRequest], + Awaitable[~.SignBlobResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignBlob", + request_serializer=common.SignBlobRequest.serialize, + response_deserializer=common.SignBlobResponse.deserialize, + ) + return self._stubs["sign_blob"] + + @property + def sign_jwt( + self, + ) -> Callable[[common.SignJwtRequest], Awaitable[common.SignJwtResponse]]: + r"""Return a callable for the sign jwt method over gRPC. + + Signs a JWT using a service account's system-managed + private key. + + Returns: + Callable[[~.SignJwtRequest], + Awaitable[~.SignJwtResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignJwt", + request_serializer=common.SignJwtRequest.serialize, + response_deserializer=common.SignJwtResponse.deserialize, + ) + return self._stubs["sign_jwt"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.generate_access_token: self._wrap_method( + self.generate_access_token, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_id_token: self._wrap_method( + self.generate_id_token, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.sign_blob: self._wrap_method( + self.sign_blob, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.sign_jwt: self._wrap_method( + self.sign_jwt, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("IAMCredentialsGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0031cf53af3df4f7b9bc8c3b14ccaaa8e4b37c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.py @@ -0,0 +1,1053 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.iam_credentials_v1.types import common + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseIAMCredentialsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class IAMCredentialsRestInterceptor: + """Interceptor for IAMCredentials. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the IAMCredentialsRestTransport. + + .. code-block:: python + class MyCustomIAMCredentialsInterceptor(IAMCredentialsRestInterceptor): + def pre_generate_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_id_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_id_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_sign_blob(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_sign_blob(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_sign_jwt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_sign_jwt(self, response): + logging.log(f"Received response: {response}") + return response + + transport = IAMCredentialsRestTransport(interceptor=MyCustomIAMCredentialsInterceptor()) + client = IAMCredentialsClient(transport=transport) + + + """ + + def pre_generate_access_token( + self, + request: common.GenerateAccessTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_generate_access_token( + self, response: common.GenerateAccessTokenResponse + ) -> common.GenerateAccessTokenResponse: + """Post-rpc interceptor for generate_access_token + + DEPRECATED. Please use the `post_generate_access_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. This `post_generate_access_token` interceptor runs + before the `post_generate_access_token_with_metadata` interceptor. + """ + return response + + def post_generate_access_token_with_metadata( + self, + response: common.GenerateAccessTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for generate_access_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the IAMCredentials server but before it is returned to user code. + + We recommend only using this `post_generate_access_token_with_metadata` + interceptor in new development instead of the `post_generate_access_token` interceptor. + When both interceptors are used, this `post_generate_access_token_with_metadata` interceptor runs after the + `post_generate_access_token` interceptor. The (possibly modified) response returned by + `post_generate_access_token` will be passed to + `post_generate_access_token_with_metadata`. + """ + return response, metadata + + def pre_generate_id_token( + self, + request: common.GenerateIdTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_id_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_generate_id_token( + self, response: common.GenerateIdTokenResponse + ) -> common.GenerateIdTokenResponse: + """Post-rpc interceptor for generate_id_token + + DEPRECATED. Please use the `post_generate_id_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. This `post_generate_id_token` interceptor runs + before the `post_generate_id_token_with_metadata` interceptor. + """ + return response + + def post_generate_id_token_with_metadata( + self, + response: common.GenerateIdTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for generate_id_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the IAMCredentials server but before it is returned to user code. + + We recommend only using this `post_generate_id_token_with_metadata` + interceptor in new development instead of the `post_generate_id_token` interceptor. + When both interceptors are used, this `post_generate_id_token_with_metadata` interceptor runs after the + `post_generate_id_token` interceptor. The (possibly modified) response returned by + `post_generate_id_token` will be passed to + `post_generate_id_token_with_metadata`. + """ + return response, metadata + + def pre_sign_blob( + self, + request: common.SignBlobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for sign_blob + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_sign_blob( + self, response: common.SignBlobResponse + ) -> common.SignBlobResponse: + """Post-rpc interceptor for sign_blob + + DEPRECATED. Please use the `post_sign_blob_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. This `post_sign_blob` interceptor runs + before the `post_sign_blob_with_metadata` interceptor. + """ + return response + + def post_sign_blob_with_metadata( + self, + response: common.SignBlobResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for sign_blob + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the IAMCredentials server but before it is returned to user code. + + We recommend only using this `post_sign_blob_with_metadata` + interceptor in new development instead of the `post_sign_blob` interceptor. + When both interceptors are used, this `post_sign_blob_with_metadata` interceptor runs after the + `post_sign_blob` interceptor. The (possibly modified) response returned by + `post_sign_blob` will be passed to + `post_sign_blob_with_metadata`. + """ + return response, metadata + + def pre_sign_jwt( + self, + request: common.SignJwtRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for sign_jwt + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_sign_jwt(self, response: common.SignJwtResponse) -> common.SignJwtResponse: + """Post-rpc interceptor for sign_jwt + + DEPRECATED. Please use the `post_sign_jwt_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. This `post_sign_jwt` interceptor runs + before the `post_sign_jwt_with_metadata` interceptor. + """ + return response + + def post_sign_jwt_with_metadata( + self, + response: common.SignJwtResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for sign_jwt + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the IAMCredentials server but before it is returned to user code. + + We recommend only using this `post_sign_jwt_with_metadata` + interceptor in new development instead of the `post_sign_jwt` interceptor. + When both interceptors are used, this `post_sign_jwt_with_metadata` interceptor runs after the + `post_sign_jwt` interceptor. The (possibly modified) response returned by + `post_sign_jwt` will be passed to + `post_sign_jwt_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class IAMCredentialsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: IAMCredentialsRestInterceptor + + +class IAMCredentialsRestTransport(_BaseIAMCredentialsRestTransport): + """REST backend synchronous transport for IAMCredentials. + + A service account is a special type of Google account that + belongs to your application or a virtual machine (VM), instead + of to an individual end user. Your application assumes the + identity of the service account to call Google APIs, so that the + users aren't directly involved. + + Service account credentials are used to temporarily assume the + identity of the service account. Supported credential types + include OAuth 2.0 access tokens, OpenID Connect ID tokens, + self-signed JSON Web Tokens (JWTs), and more. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[IAMCredentialsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or IAMCredentialsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GenerateAccessToken( + _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, + IAMCredentialsRestStub, + ): + def __hash__(self): + return hash("IAMCredentialsRestTransport.GenerateAccessToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: common.GenerateAccessTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: + r"""Call the generate access token method over HTTP. + + Args: + request (~.common.GenerateAccessTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.common.GenerateAccessTokenResponse: + + """ + + http_options = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_access_token( + request, metadata + ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request( + http_options, request + ) + + body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateAccessToken", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "GenerateAccessToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IAMCredentialsRestTransport._GenerateAccessToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.GenerateAccessTokenResponse() + pb_resp = common.GenerateAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_access_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_access_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = common.GenerateAccessTokenResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_access_token", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "GenerateAccessToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateIdToken( + _BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub + ): + def __hash__(self): + return hash("IAMCredentialsRestTransport.GenerateIdToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: common.GenerateIdTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: + r"""Call the generate id token method over HTTP. + + Args: + request (~.common.GenerateIdTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.common.GenerateIdTokenResponse: + + """ + + http_options = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_id_token( + request, metadata + ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request( + http_options, request + ) + + body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateIdToken", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "GenerateIdToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IAMCredentialsRestTransport._GenerateIdToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.GenerateIdTokenResponse() + pb_resp = common.GenerateIdTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_id_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_id_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = common.GenerateIdTokenResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_id_token", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "GenerateIdToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SignBlob( + _BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub + ): + def __hash__(self): + return hash("IAMCredentialsRestTransport.SignBlob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: common.SignBlobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: + r"""Call the sign blob method over HTTP. + + Args: + request (~.common.SignBlobRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.common.SignBlobResponse: + + """ + + http_options = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() + ) + + request, metadata = self._interceptor.pre_sign_blob(request, metadata) + transcoded_request = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignBlob", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "SignBlob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IAMCredentialsRestTransport._SignBlob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.SignBlobResponse() + pb_resp = common.SignBlobResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_sign_blob(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_sign_blob_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = common.SignBlobResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_blob", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "SignBlob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SignJwt( + _BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub + ): + def __hash__(self): + return hash("IAMCredentialsRestTransport.SignJwt") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: common.SignJwtRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: + r"""Call the sign jwt method over HTTP. + + Args: + request (~.common.SignJwtRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.common.SignJwtResponse: + + """ + + http_options = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() + ) + + request, metadata = self._interceptor.pre_sign_jwt(request, metadata) + transcoded_request = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignJwt", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "SignJwt", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IAMCredentialsRestTransport._SignJwt._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.SignJwtResponse() + pb_resp = common.SignJwtResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_sign_jwt(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_sign_jwt_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = common.SignJwtResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_jwt", + extra={ + "serviceName": "google.iam.credentials.v1.IAMCredentials", + "rpcName": "SignJwt", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore + + @property + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("IAMCredentialsRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd251feea91e58e98a683ebb2a83d95d6d674fd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest_base.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.iam_credentials_v1.types import common + +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport + + +class _BaseIAMCredentialsRestTransport(IAMCredentialsTransport): + """Base REST backend transport for IAMCredentials. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGenerateAccessToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = common.GenerateAccessTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateIdToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateIdToken", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = common.GenerateIdTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSignBlob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:signBlob", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = common.SignBlobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSignJwt: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:signJwt", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = common.SignJwtRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseIAMCredentialsRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3846fefa8fbdf062a8ffe5b7cb2b3aa4048eb63 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GenerateIdTokenRequest, + GenerateIdTokenResponse, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, +) + +__all__ = ( + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/common.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f42dd93afee53d13c088b0b7c01944b7f83780 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/common.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.credentials.v1", + manifest={ + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + }, +) + + +class GenerateAccessTokenRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The resource name of the service account for which + the credentials are requested, in the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. Each + service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its next + service account in the chain. The last service account in + the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the service + account that is specified in the ``name`` field of the + request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + scope (MutableSequence[str]): + Required. Code to identify the scopes to be + included in the OAuth 2.0 access token. See + https://developers.google.com/identity/protocols/googlescopes + for more information. + At least one value required. + lifetime (google.protobuf.duration_pb2.Duration): + The desired lifetime duration of the access + token in seconds. Must be set to a value less + than or equal to 3600 (1 hour). If a value is + not specified, the token's lifetime will be set + to a default value of one hour. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + delegates: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + scope: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + lifetime: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + +class GenerateAccessTokenResponse(proto.Message): + r""" + + Attributes: + access_token (str): + The OAuth 2.0 access token. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Token expiration time. + The expiration time is always set. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class SignBlobRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The resource name of the service account for which + the credentials are requested, in the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. Each + service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its next + service account in the chain. The last service account in + the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the service + account that is specified in the ``name`` field of the + request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + payload (bytes): + Required. The bytes to sign. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + delegates: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + payload: bytes = proto.Field( + proto.BYTES, + number=5, + ) + + +class SignBlobResponse(proto.Message): + r""" + + Attributes: + key_id (str): + The ID of the key used to sign the blob. + signed_blob (bytes): + The signed blob. + """ + + key_id: str = proto.Field( + proto.STRING, + number=1, + ) + signed_blob: bytes = proto.Field( + proto.BYTES, + number=4, + ) + + +class SignJwtRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The resource name of the service account for which + the credentials are requested, in the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. Each + service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its next + service account in the chain. The last service account in + the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the service + account that is specified in the ``name`` field of the + request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + payload (str): + Required. The JWT payload to sign: a JSON + object that contains a JWT Claims Set. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + delegates: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + payload: str = proto.Field( + proto.STRING, + number=5, + ) + + +class SignJwtResponse(proto.Message): + r""" + + Attributes: + key_id (str): + The ID of the key used to sign the JWT. + signed_jwt (str): + The signed JWT. + """ + + key_id: str = proto.Field( + proto.STRING, + number=1, + ) + signed_jwt: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateIdTokenRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The resource name of the service account for which + the credentials are requested, in the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + delegates (MutableSequence[str]): + The sequence of service accounts in a delegation chain. Each + service account must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on its next + service account in the chain. The last service account in + the chain must be granted the + ``roles/iam.serviceAccountTokenCreator`` role on the service + account that is specified in the ``name`` field of the + request. + + The delegates must have the following format: + ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. + The ``-`` wildcard character is required; replacing it with + a project ID is invalid. + audience (str): + Required. The audience for the token, such as + the API or account that this token grants access + to. + include_email (bool): + Include the service account email in the token. If set to + ``true``, the token will contain ``email`` and + ``email_verified`` claims. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + delegates: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + audience: str = proto.Field( + proto.STRING, + number=3, + ) + include_email: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GenerateIdTokenResponse(proto.Message): + r""" + + Attributes: + token (str): + The OpenId Connect ID token. + """ + + token: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/iamcredentials.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/iamcredentials.py new file mode 100644 index 0000000000000000000000000000000000000000..1616a02036f568a5551ff7970bab734038ce2dec --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_credentials_v1/types/iamcredentials.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.credentials.v1", + manifest={}, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c2c753ecea23230478a8ad27f8358b43e318c87 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/__init__.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.iam_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.policies import PoliciesAsyncClient, PoliciesClient +from .types.deny import DenyRule +from .types.policy import ( + CreatePolicyRequest, + DeletePolicyRequest, + GetPolicyRequest, + ListPoliciesRequest, + ListPoliciesResponse, + Policy, + PolicyOperationMetadata, + PolicyRule, + UpdatePolicyRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.iam_v2") # type: ignore + api_core.check_dependency_versions("google.cloud.iam_v2") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.iam_v2" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "PoliciesAsyncClient", + "CreatePolicyRequest", + "DeletePolicyRequest", + "DenyRule", + "GetPolicyRequest", + "ListPoliciesRequest", + "ListPoliciesResponse", + "PoliciesClient", + "Policy", + "PolicyOperationMetadata", + "PolicyRule", + "UpdatePolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..ccdb1fdedfba616d06d7d971813c09a2a926d1d8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_v2", + "protoPackage": "google.iam.v2", + "schema": "1.0", + "services": { + "Policies": { + "clients": { + "grpc": { + "libraryClient": "PoliciesClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PoliciesAsyncClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + }, + "rest": { + "libraryClient": "PoliciesClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a031b8d466972f8e0b3509ee43a1d166d4c3df2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PoliciesAsyncClient +from .client import PoliciesClient + +__all__ = ( + "PoliciesClient", + "PoliciesAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..8f242ac62ab117666b530a146a553c039b23617a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/async_client.py @@ -0,0 +1,1031 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v2.services.policies import pagers +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .client import PoliciesClient +from .transports.base import DEFAULT_CLIENT_INFO, PoliciesTransport +from .transports.grpc_asyncio import PoliciesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PoliciesAsyncClient: + """An interface for managing Identity and Access Management + (IAM) policies. + """ + + _client: PoliciesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PoliciesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PoliciesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PoliciesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PoliciesClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod( + PoliciesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PoliciesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(PoliciesClient.common_folder_path) + parse_common_folder_path = staticmethod(PoliciesClient.parse_common_folder_path) + common_organization_path = staticmethod(PoliciesClient.common_organization_path) + parse_common_organization_path = staticmethod( + PoliciesClient.parse_common_organization_path + ) + common_project_path = staticmethod(PoliciesClient.common_project_path) + parse_common_project_path = staticmethod(PoliciesClient.parse_common_project_path) + common_location_path = staticmethod(PoliciesClient.common_location_path) + parse_common_location_path = staticmethod(PoliciesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesAsyncClient: The constructed client. + """ + sa_info_func = ( + PoliciesClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(PoliciesAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesAsyncClient: The constructed client. + """ + sa_file_func = ( + PoliciesClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(PoliciesAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PoliciesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PoliciesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PoliciesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PoliciesTransport, Callable[..., PoliciesTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policies async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PoliciesTransport,Callable[..., PoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PoliciesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v2.PoliciesAsyncClient`.", + extra={ + "serviceName": "google.iam.v2.Policies", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.v2.Policies", + "credentialsType": None, + }, + ) + + async def list_policies( + self, + request: Optional[Union[policy.ListPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPoliciesAsyncPager: + r"""Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + async def sample_list_policies(): + # Create a client + client = iam_v2.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2.ListPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2.types.ListPoliciesRequest, dict]]): + The request object. Request message for ``ListPolicies``. + parent (:class:`str`): + Required. The resource that the policy is attached to, + along with the kind of policy to list. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2.services.policies.pagers.ListPoliciesAsyncPager: + Response message for ListPolicies. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.ListPoliciesRequest): + request = policy.ListPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_policy( + self, + request: Optional[Union[policy.GetPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy.Policy: + r"""Gets a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + async def sample_get_policy(): + # Create a client + client = iam_v2.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2.GetPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2.types.GetPolicyRequest, dict]]): + The request object. Request message for ``GetPolicy``. + name (:class:`str`): + Required. The resource name of the policy to retrieve. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2.types.Policy: + Data for an IAM policy. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.GetPolicyRequest): + request = policy.GetPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_policy( + self, + request: Optional[Union[gi_policy.CreatePolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + policy: Optional[gi_policy.Policy] = None, + policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + async def sample_create_policy(): + # Create a client + client = iam_v2.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2.CreatePolicyRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2.types.CreatePolicyRequest, dict]]): + The request object. Request message for ``CreatePolicy``. + parent (:class:`str`): + Required. The resource that the policy is attached to, + along with the kind of policy to create. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy (:class:`google.cloud.iam_v2.types.Policy`): + Required. The policy to create. + This corresponds to the ``policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_id (:class:`str`): + The ID to use for this policy, which will become the + final component of the policy's resource name. The ID + must contain 3 to 63 characters. It can contain + lowercase letters and numbers, as well as dashes (``-``) + and periods (``.``). The first character must be a + lowercase letter. + + This corresponds to the ``policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2.types.Policy` Data for an + IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy, policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gi_policy.CreatePolicyRequest): + request = gi_policy.CreatePolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy is not None: + request.policy = policy + if policy_id is not None: + request.policy_id = policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gi_policy.Policy, + metadata_type=gi_policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_policy( + self, + request: Optional[Union[policy.UpdatePolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2.Policies.GetPolicy] to read the + current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + async def sample_update_policy(): + # Create a client + client = iam_v2.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2.UpdatePolicyRequest( + ) + + # Make the request + operation = client.update_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2.types.UpdatePolicyRequest, dict]]): + The request object. Request message for ``UpdatePolicy``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2.types.Policy` Data for an + IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.UpdatePolicyRequest): + request = policy.UpdatePolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy.name", request.policy.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_policy( + self, + request: Optional[Union[policy.DeletePolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a policy. This action is permanent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + async def sample_delete_policy(): + # Create a client + client = iam_v2.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2.DeletePolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2.types.DeletePolicyRequest, dict]]): + The request object. Request message for ``DeletePolicy``. + name (:class:`str`): + Required. The resource name of the policy to delete. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2.types.Policy` Data for an + IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.DeletePolicyRequest): + request = policy.DeletePolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PoliciesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PoliciesAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/client.py new file mode 100644 index 0000000000000000000000000000000000000000..16b2dcb59777567bc907b52a8b21b528965a9764 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/client.py @@ -0,0 +1,1446 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v2.services.policies import pagers +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .transports.base import DEFAULT_CLIENT_INFO, PoliciesTransport +from .transports.grpc import PoliciesGrpcTransport +from .transports.grpc_asyncio import PoliciesGrpcAsyncIOTransport +from .transports.rest import PoliciesRestTransport + + +class PoliciesClientMeta(type): + """Metaclass for the Policies client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PoliciesTransport]] + _transport_registry["grpc"] = PoliciesGrpcTransport + _transport_registry["grpc_asyncio"] = PoliciesGrpcAsyncIOTransport + _transport_registry["rest"] = PoliciesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PoliciesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PoliciesClient(metaclass=PoliciesClientMeta): + """An interface for managing Identity and Access Management + (IAM) policies. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PoliciesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = PoliciesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = PoliciesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PoliciesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PoliciesTransport, Callable[..., PoliciesTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policies client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PoliciesTransport,Callable[..., PoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PoliciesClient._read_environment_variables() + ) + self._client_cert_source = PoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, PoliciesTransport) + if transport_provided: + # transport is a PoliciesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or PoliciesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PoliciesTransport], Callable[..., PoliciesTransport] + ] = ( + PoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PoliciesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v2.PoliciesClient`.", + extra={ + "serviceName": "google.iam.v2.Policies", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.v2.Policies", + "credentialsType": None, + }, + ) + + def list_policies( + self, + request: Optional[Union[policy.ListPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPoliciesPager: + r"""Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + def sample_list_policies(): + # Create a client + client = iam_v2.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2.ListPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v2.types.ListPoliciesRequest, dict]): + The request object. Request message for ``ListPolicies``. + parent (str): + Required. The resource that the policy is attached to, + along with the kind of policy to list. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2.services.policies.pagers.ListPoliciesPager: + Response message for ListPolicies. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.ListPoliciesRequest): + request = policy.ListPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_policy( + self, + request: Optional[Union[policy.GetPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy.Policy: + r"""Gets a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + def sample_get_policy(): + # Create a client + client = iam_v2.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2.GetPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2.types.GetPolicyRequest, dict]): + The request object. Request message for ``GetPolicy``. + name (str): + Required. The resource name of the policy to retrieve. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2.types.Policy: + Data for an IAM policy. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.GetPolicyRequest): + request = policy.GetPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_policy( + self, + request: Optional[Union[gi_policy.CreatePolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + policy: Optional[gi_policy.Policy] = None, + policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + def sample_create_policy(): + # Create a client + client = iam_v2.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2.CreatePolicyRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2.types.CreatePolicyRequest, dict]): + The request object. Request message for ``CreatePolicy``. + parent (str): + Required. The resource that the policy is attached to, + along with the kind of policy to create. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy (google.cloud.iam_v2.types.Policy): + Required. The policy to create. + This corresponds to the ``policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_id (str): + The ID to use for this policy, which will become the + final component of the policy's resource name. The ID + must contain 3 to 63 characters. It can contain + lowercase letters and numbers, as well as dashes (``-``) + and periods (``.``). The first character must be a + lowercase letter. + + This corresponds to the ``policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2.types.Policy` Data for an + IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy, policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gi_policy.CreatePolicyRequest): + request = gi_policy.CreatePolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy is not None: + request.policy = policy + if policy_id is not None: + request.policy_id = policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gi_policy.Policy, + metadata_type=gi_policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + def update_policy( + self, + request: Optional[Union[policy.UpdatePolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2.Policies.GetPolicy] to read the + current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + def sample_update_policy(): + # Create a client + client = iam_v2.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2.UpdatePolicyRequest( + ) + + # Make the request + operation = client.update_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2.types.UpdatePolicyRequest, dict]): + The request object. Request message for ``UpdatePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2.types.Policy` Data for an + IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.UpdatePolicyRequest): + request = policy.UpdatePolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy.name", request.policy.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + def delete_policy( + self, + request: Optional[Union[policy.DeletePolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a policy. This action is permanent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2 + + def sample_delete_policy(): + # Create a client + client = iam_v2.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2.DeletePolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2.types.DeletePolicyRequest, dict]): + The request object. Request message for ``DeletePolicy``. + name (str): + Required. The resource name of the policy to delete. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2.types.Policy` Data for an + IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.DeletePolicyRequest): + request = policy.DeletePolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PoliciesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PoliciesClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..7faccfbb9293e25a41739393af7462bb2a97c1ba --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_v2.types import policy + + +class ListPoliciesPager: + """A pager for iterating through ``list_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v2.types.ListPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicies`` requests and continue to iterate + through the ``policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v2.types.ListPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., policy.ListPoliciesResponse], + request: policy.ListPoliciesRequest, + response: policy.ListPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v2.types.ListPoliciesRequest): + The initial request object. + response (google.cloud.iam_v2.types.ListPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy.ListPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policy.ListPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy.Policy]: + for page in self.pages: + yield from page.policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPoliciesAsyncPager: + """A pager for iterating through ``list_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v2.types.ListPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicies`` requests and continue to iterate + through the ``policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v2.types.ListPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[policy.ListPoliciesResponse]], + request: policy.ListPoliciesRequest, + response: policy.ListPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v2.types.ListPoliciesRequest): + The initial request object. + response (google.cloud.iam_v2.types.ListPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy.ListPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[policy.ListPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy.Policy]: + async def async_generator(): + async for page in self.pages: + for response in page.policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3177a9f1ffc1bc9815e53875daabce8569340cf1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PoliciesTransport +from .grpc import PoliciesGrpcTransport +from .grpc_asyncio import PoliciesGrpcAsyncIOTransport +from .rest import PoliciesRestInterceptor, PoliciesRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PoliciesTransport]] +_transport_registry["grpc"] = PoliciesGrpcTransport +_transport_registry["grpc_asyncio"] = PoliciesGrpcAsyncIOTransport +_transport_registry["rest"] = PoliciesRestTransport + +__all__ = ( + "PoliciesTransport", + "PoliciesGrpcTransport", + "PoliciesGrpcAsyncIOTransport", + "PoliciesRestTransport", + "PoliciesRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1733c65e41406fa0ce989ebd76fab860fd259c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/base.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v2 import gapic_version as package_version +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PoliciesTransport(abc.ABC): + """Abstract transport class for Policies.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_policies: gapic_v1.method.wrap_method( + self.list_policies, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_policy: gapic_v1.method.wrap_method( + self.get_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_policy: gapic_v1.method.wrap_method( + self.create_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy: gapic_v1.method.wrap_method( + self.update_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_policy: gapic_v1.method.wrap_method( + self.delete_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_policies( + self, + ) -> Callable[ + [policy.ListPoliciesRequest], + Union[policy.ListPoliciesResponse, Awaitable[policy.ListPoliciesResponse]], + ]: + raise NotImplementedError() + + @property + def get_policy( + self, + ) -> Callable[ + [policy.GetPolicyRequest], Union[policy.Policy, Awaitable[policy.Policy]] + ]: + raise NotImplementedError() + + @property + def create_policy( + self, + ) -> Callable[ + [gi_policy.CreatePolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_policy( + self, + ) -> Callable[ + [policy.UpdatePolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_policy( + self, + ) -> Callable[ + [policy.DeletePolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PoliciesTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..2de58f7229fe0ca8d1501131aed98149775238c0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/grpc.py @@ -0,0 +1,517 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO, PoliciesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PoliciesGrpcTransport(PoliciesTransport): + """gRPC backend transport for Policies. + + An interface for managing Identity and Access Management + (IAM) policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_policies( + self, + ) -> Callable[[policy.ListPoliciesRequest], policy.ListPoliciesResponse]: + r"""Return a callable for the list policies method over gRPC. + + Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + Returns: + Callable[[~.ListPoliciesRequest], + ~.ListPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policies" not in self._stubs: + self._stubs["list_policies"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/ListPolicies", + request_serializer=policy.ListPoliciesRequest.serialize, + response_deserializer=policy.ListPoliciesResponse.deserialize, + ) + return self._stubs["list_policies"] + + @property + def get_policy(self) -> Callable[[policy.GetPolicyRequest], policy.Policy]: + r"""Return a callable for the get policy method over gRPC. + + Gets a policy. + + Returns: + Callable[[~.GetPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy" not in self._stubs: + self._stubs["get_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/GetPolicy", + request_serializer=policy.GetPolicyRequest.serialize, + response_deserializer=policy.Policy.deserialize, + ) + return self._stubs["get_policy"] + + @property + def create_policy( + self, + ) -> Callable[[gi_policy.CreatePolicyRequest], operations_pb2.Operation]: + r"""Return a callable for the create policy method over gRPC. + + Creates a policy. + + Returns: + Callable[[~.CreatePolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy" not in self._stubs: + self._stubs["create_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/CreatePolicy", + request_serializer=gi_policy.CreatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy"] + + @property + def update_policy( + self, + ) -> Callable[[policy.UpdatePolicyRequest], operations_pb2.Operation]: + r"""Return a callable for the update policy method over gRPC. + + Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2.Policies.GetPolicy] to read the + current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + Returns: + Callable[[~.UpdatePolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy" not in self._stubs: + self._stubs["update_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/UpdatePolicy", + request_serializer=policy.UpdatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy"] + + @property + def delete_policy( + self, + ) -> Callable[[policy.DeletePolicyRequest], operations_pb2.Operation]: + r"""Return a callable for the delete policy method over gRPC. + + Deletes a policy. This action is permanent. + + Returns: + Callable[[~.DeletePolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy" not in self._stubs: + self._stubs["delete_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/DeletePolicy", + request_serializer=policy.DeletePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PoliciesGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..efffd3af56fc7e1493ad2d07c318492b3aa009e2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/grpc_asyncio.py @@ -0,0 +1,612 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO, PoliciesTransport +from .grpc import PoliciesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PoliciesGrpcAsyncIOTransport(PoliciesTransport): + """gRPC AsyncIO backend transport for Policies. + + An interface for managing Identity and Access Management + (IAM) policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_policies( + self, + ) -> Callable[[policy.ListPoliciesRequest], Awaitable[policy.ListPoliciesResponse]]: + r"""Return a callable for the list policies method over gRPC. + + Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + Returns: + Callable[[~.ListPoliciesRequest], + Awaitable[~.ListPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policies" not in self._stubs: + self._stubs["list_policies"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/ListPolicies", + request_serializer=policy.ListPoliciesRequest.serialize, + response_deserializer=policy.ListPoliciesResponse.deserialize, + ) + return self._stubs["list_policies"] + + @property + def get_policy( + self, + ) -> Callable[[policy.GetPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get policy method over gRPC. + + Gets a policy. + + Returns: + Callable[[~.GetPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy" not in self._stubs: + self._stubs["get_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/GetPolicy", + request_serializer=policy.GetPolicyRequest.serialize, + response_deserializer=policy.Policy.deserialize, + ) + return self._stubs["get_policy"] + + @property + def create_policy( + self, + ) -> Callable[[gi_policy.CreatePolicyRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create policy method over gRPC. + + Creates a policy. + + Returns: + Callable[[~.CreatePolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy" not in self._stubs: + self._stubs["create_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/CreatePolicy", + request_serializer=gi_policy.CreatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy"] + + @property + def update_policy( + self, + ) -> Callable[[policy.UpdatePolicyRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update policy method over gRPC. + + Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2.Policies.GetPolicy] to read the + current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + Returns: + Callable[[~.UpdatePolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy" not in self._stubs: + self._stubs["update_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/UpdatePolicy", + request_serializer=policy.UpdatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy"] + + @property + def delete_policy( + self, + ) -> Callable[[policy.DeletePolicyRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete policy method over gRPC. + + Deletes a policy. This action is permanent. + + Returns: + Callable[[~.DeletePolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy" not in self._stubs: + self._stubs["delete_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2.Policies/DeletePolicy", + request_serializer=policy.DeletePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_policies: self._wrap_method( + self.list_policies, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_policy: self._wrap_method( + self.get_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_policy: self._wrap_method( + self.create_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy: self._wrap_method( + self.update_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_policy: self._wrap_method( + self.delete_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("PoliciesGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2649a9e0f7b213f1b6c7d43566544b44013a93 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/rest.py @@ -0,0 +1,1435 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePoliciesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PoliciesRestInterceptor: + """Interceptor for Policies. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PoliciesRestTransport. + + .. code-block:: python + class MyCustomPoliciesInterceptor(PoliciesRestInterceptor): + def pre_create_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PoliciesRestTransport(interceptor=MyCustomPoliciesInterceptor()) + client = PoliciesClient(transport=transport) + + + """ + + def pre_create_policy( + self, + request: gi_policy.CreatePolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gi_policy.CreatePolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_create_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_policy + + DEPRECATED. Please use the `post_create_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Policies server but before + it is returned to user code. This `post_create_policy` interceptor runs + before the `post_create_policy_with_metadata` interceptor. + """ + return response + + def post_create_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Policies server but before it is returned to user code. + + We recommend only using this `post_create_policy_with_metadata` + interceptor in new development instead of the `post_create_policy` interceptor. + When both interceptors are used, this `post_create_policy_with_metadata` interceptor runs after the + `post_create_policy` interceptor. The (possibly modified) response returned by + `post_create_policy` will be passed to + `post_create_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_policy( + self, + request: policy.DeletePolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy.DeletePolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_delete_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_policy + + DEPRECATED. Please use the `post_delete_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Policies server but before + it is returned to user code. This `post_delete_policy` interceptor runs + before the `post_delete_policy_with_metadata` interceptor. + """ + return response + + def post_delete_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Policies server but before it is returned to user code. + + We recommend only using this `post_delete_policy_with_metadata` + interceptor in new development instead of the `post_delete_policy` interceptor. + When both interceptors are used, this `post_delete_policy_with_metadata` interceptor runs after the + `post_delete_policy` interceptor. The (possibly modified) response returned by + `post_delete_policy` will be passed to + `post_delete_policy_with_metadata`. + """ + return response, metadata + + def pre_get_policy( + self, + request: policy.GetPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy.GetPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_get_policy(self, response: policy.Policy) -> policy.Policy: + """Post-rpc interceptor for get_policy + + DEPRECATED. Please use the `post_get_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Policies server but before + it is returned to user code. This `post_get_policy` interceptor runs + before the `post_get_policy_with_metadata` interceptor. + """ + return response + + def post_get_policy_with_metadata( + self, response: policy.Policy, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[policy.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Policies server but before it is returned to user code. + + We recommend only using this `post_get_policy_with_metadata` + interceptor in new development instead of the `post_get_policy` interceptor. + When both interceptors are used, this `post_get_policy_with_metadata` interceptor runs after the + `post_get_policy` interceptor. The (possibly modified) response returned by + `post_get_policy` will be passed to + `post_get_policy_with_metadata`. + """ + return response, metadata + + def pre_list_policies( + self, + request: policy.ListPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy.ListPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_list_policies( + self, response: policy.ListPoliciesResponse + ) -> policy.ListPoliciesResponse: + """Post-rpc interceptor for list_policies + + DEPRECATED. Please use the `post_list_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Policies server but before + it is returned to user code. This `post_list_policies` interceptor runs + before the `post_list_policies_with_metadata` interceptor. + """ + return response + + def post_list_policies_with_metadata( + self, + response: policy.ListPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy.ListPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Policies server but before it is returned to user code. + + We recommend only using this `post_list_policies_with_metadata` + interceptor in new development instead of the `post_list_policies` interceptor. + When both interceptors are used, this `post_list_policies_with_metadata` interceptor runs after the + `post_list_policies` interceptor. The (possibly modified) response returned by + `post_list_policies` will be passed to + `post_list_policies_with_metadata`. + """ + return response, metadata + + def pre_update_policy( + self, + request: policy.UpdatePolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy.UpdatePolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_update_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_policy + + DEPRECATED. Please use the `post_update_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Policies server but before + it is returned to user code. This `post_update_policy` interceptor runs + before the `post_update_policy_with_metadata` interceptor. + """ + return response + + def post_update_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Policies server but before it is returned to user code. + + We recommend only using this `post_update_policy_with_metadata` + interceptor in new development instead of the `post_update_policy` interceptor. + When both interceptors are used, this `post_update_policy_with_metadata` interceptor runs after the + `post_update_policy` interceptor. The (possibly modified) response returned by + `post_update_policy` will be passed to + `post_update_policy_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PoliciesRestInterceptor + + +class PoliciesRestTransport(_BasePoliciesRestTransport): + """REST backend synchronous transport for Policies. + + An interface for managing Identity and Access Management + (IAM) policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PoliciesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[PoliciesRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PoliciesRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=policies/*/*/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePolicy(_BasePoliciesRestTransport._BaseCreatePolicy, PoliciesRestStub): + def __hash__(self): + return hash("PoliciesRestTransport.CreatePolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gi_policy.CreatePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create policy method over HTTP. + + Args: + request (~.gi_policy.CreatePolicyRequest): + The request object. Request message for ``CreatePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BasePoliciesRestTransport._BaseCreatePolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_policy(request, metadata) + transcoded_request = ( + _BasePoliciesRestTransport._BaseCreatePolicy._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePoliciesRestTransport._BaseCreatePolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePoliciesRestTransport._BaseCreatePolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v2.PoliciesClient.CreatePolicy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "CreatePolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PoliciesRestTransport._CreatePolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v2.PoliciesClient.create_policy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "CreatePolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePolicy(_BasePoliciesRestTransport._BaseDeletePolicy, PoliciesRestStub): + def __hash__(self): + return hash("PoliciesRestTransport.DeletePolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy.DeletePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete policy method over HTTP. + + Args: + request (~.policy.DeletePolicyRequest): + The request object. Request message for ``DeletePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BasePoliciesRestTransport._BaseDeletePolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_policy(request, metadata) + transcoded_request = ( + _BasePoliciesRestTransport._BaseDeletePolicy._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePoliciesRestTransport._BaseDeletePolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v2.PoliciesClient.DeletePolicy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "DeletePolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PoliciesRestTransport._DeletePolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v2.PoliciesClient.delete_policy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "DeletePolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPolicy(_BasePoliciesRestTransport._BaseGetPolicy, PoliciesRestStub): + def __hash__(self): + return hash("PoliciesRestTransport.GetPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy.GetPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy.Policy: + r"""Call the get policy method over HTTP. + + Args: + request (~.policy.GetPolicyRequest): + The request object. Request message for ``GetPolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy.Policy: + Data for an IAM policy. + """ + + http_options = _BasePoliciesRestTransport._BaseGetPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_policy(request, metadata) + transcoded_request = ( + _BasePoliciesRestTransport._BaseGetPolicy._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePoliciesRestTransport._BaseGetPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v2.PoliciesClient.GetPolicy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "GetPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PoliciesRestTransport._GetPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy.Policy() + pb_resp = policy.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = policy.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v2.PoliciesClient.get_policy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "GetPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPolicies(_BasePoliciesRestTransport._BaseListPolicies, PoliciesRestStub): + def __hash__(self): + return hash("PoliciesRestTransport.ListPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy.ListPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy.ListPoliciesResponse: + r"""Call the list policies method over HTTP. + + Args: + request (~.policy.ListPoliciesRequest): + The request object. Request message for ``ListPolicies``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy.ListPoliciesResponse: + Response message for ``ListPolicies``. + """ + + http_options = ( + _BasePoliciesRestTransport._BaseListPolicies._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_policies(request, metadata) + transcoded_request = ( + _BasePoliciesRestTransport._BaseListPolicies._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePoliciesRestTransport._BaseListPolicies._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v2.PoliciesClient.ListPolicies", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "ListPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PoliciesRestTransport._ListPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy.ListPoliciesResponse() + pb_resp = policy.ListPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = policy.ListPoliciesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v2.PoliciesClient.list_policies", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "ListPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePolicy(_BasePoliciesRestTransport._BaseUpdatePolicy, PoliciesRestStub): + def __hash__(self): + return hash("PoliciesRestTransport.UpdatePolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: policy.UpdatePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update policy method over HTTP. + + Args: + request (~.policy.UpdatePolicyRequest): + The request object. Request message for ``UpdatePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BasePoliciesRestTransport._BaseUpdatePolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_policy(request, metadata) + transcoded_request = ( + _BasePoliciesRestTransport._BaseUpdatePolicy._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePoliciesRestTransport._BaseUpdatePolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePoliciesRestTransport._BaseUpdatePolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v2.PoliciesClient.UpdatePolicy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "UpdatePolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PoliciesRestTransport._UpdatePolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v2.PoliciesClient.update_policy", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "UpdatePolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_policy( + self, + ) -> Callable[[gi_policy.CreatePolicyRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_policy( + self, + ) -> Callable[[policy.DeletePolicyRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_policy(self) -> Callable[[policy.GetPolicyRequest], policy.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_policies( + self, + ) -> Callable[[policy.ListPoliciesRequest], policy.ListPoliciesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_policy( + self, + ) -> Callable[[policy.UpdatePolicyRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BasePoliciesRestTransport._BaseGetOperation, PoliciesRestStub): + def __hash__(self): + return hash("PoliciesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BasePoliciesRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BasePoliciesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePoliciesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v2.PoliciesClient.GetOperation", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PoliciesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v2.PoliciesAsyncClient.GetOperation", + extra={ + "serviceName": "google.iam.v2.Policies", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PoliciesRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..eec86a5f741ff5b0d2a6a39c1141d3741c677c9d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/services/policies/transports/rest_base.py @@ -0,0 +1,373 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO, PoliciesTransport + + +class _BasePoliciesRestTransport(PoliciesTransport): + """Base REST backend transport for Policies. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=policies/*/*}", + "body": "policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gi_policy.CreatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePoliciesRestTransport._BaseCreatePolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=policies/*/*/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy.DeletePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePoliciesRestTransport._BaseDeletePolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=policies/*/*/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy.GetPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePoliciesRestTransport._BaseGetPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=policies/*/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy.ListPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePoliciesRestTransport._BaseListPolicies._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v2/{policy.name=policies/*/*/*}", + "body": "policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy.UpdatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePoliciesRestTransport._BaseUpdatePolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=policies/*/*/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePoliciesRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..995b92b87cc94ecdc1ba3adcc64a3c19abd500cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .deny import ( + DenyRule, +) +from .policy import ( + CreatePolicyRequest, + DeletePolicyRequest, + GetPolicyRequest, + ListPoliciesRequest, + ListPoliciesResponse, + Policy, + PolicyOperationMetadata, + PolicyRule, + UpdatePolicyRequest, +) + +__all__ = ( + "DenyRule", + "CreatePolicyRequest", + "DeletePolicyRequest", + "GetPolicyRequest", + "ListPoliciesRequest", + "ListPoliciesResponse", + "Policy", + "PolicyOperationMetadata", + "PolicyRule", + "UpdatePolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/deny.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/deny.py new file mode 100644 index 0000000000000000000000000000000000000000..bc70778530cf63912d7ac73db35156f913df1b79 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/deny.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.type.expr_pb2 as expr_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v2", + manifest={ + "DenyRule", + }, +) + + +class DenyRule(proto.Message): + r"""A deny rule in an IAM deny policy. + + Attributes: + denied_principals (MutableSequence[str]): + The identities that are prevented from using one or more + permissions on Google Cloud resources. This field can + contain the following values: + + - ``principalSet://goog/public:all``: A special identifier + that represents any principal that is on the internet, + even if they do not have a Google Account or are not + logged in. + + - ``principal://goog/subject/{email_id}``: A specific Google + Account. Includes Gmail, Cloud Identity, and Google + Workspace user accounts. For example, + ``principal://goog/subject/alice@example.com``. + + - ``deleted:principal://goog/subject/{email_id}?uid={uid}``: + A specific Google Account that was deleted recently. For + example, + ``deleted:principal://goog/subject/alice@example.com?uid=1234567890``. + If the Google Account is recovered, this identifier + reverts to the standard identifier for a Google Account. + + - ``principalSet://goog/group/{group_id}``: A Google group. + For example, + ``principalSet://goog/group/admins@example.com``. + + - ``deleted:principalSet://goog/group/{group_id}?uid={uid}``: + A Google group that was deleted recently. For example, + ``deleted:principalSet://goog/group/admins@example.com?uid=1234567890``. + If the Google group is restored, this identifier reverts + to the standard identifier for a Google group. + + - ``principal://iam.googleapis.com/projects/-/serviceAccounts/{service_account_id}``: + A Google Cloud service account. For example, + ``principal://iam.googleapis.com/projects/-/serviceAccounts/my-service-account@iam.gserviceaccount.com``. + + - ``deleted:principal://iam.googleapis.com/projects/-/serviceAccounts/{service_account_id}?uid={uid}``: + A Google Cloud service account that was deleted recently. + For example, + ``deleted:principal://iam.googleapis.com/projects/-/serviceAccounts/my-service-account@iam.gserviceaccount.com?uid=1234567890``. + If the service account is undeleted, this identifier + reverts to the standard identifier for a service account. + + - ``principalSet://goog/cloudIdentityCustomerId/{customer_id}``: + All of the principals associated with the specified Google + Workspace or Cloud Identity customer ID. For example, + ``principalSet://goog/cloudIdentityCustomerId/C01Abc35``. + exception_principals (MutableSequence[str]): + The identities that are excluded from the deny rule, even if + they are listed in the ``denied_principals``. For example, + you could add a Google group to the ``denied_principals``, + then exclude specific users who belong to that group. + + This field can contain the same values as the + ``denied_principals`` field, excluding + ``principalSet://goog/public:all``, which represents all + users on the internet. + denied_permissions (MutableSequence[str]): + The permissions that are explicitly denied by this rule. + Each permission uses the format + ``{service_fqdn}/{resource}.{verb}``, where + ``{service_fqdn}`` is the fully qualified domain name for + the service. For example, ``iam.googleapis.com/roles.list``. + exception_permissions (MutableSequence[str]): + Specifies the permissions that this rule excludes from the + set of denied permissions given by ``denied_permissions``. + If a permission appears in ``denied_permissions`` *and* in + ``exception_permissions`` then it will *not* be denied. + + The excluded permissions can be specified using the same + syntax as ``denied_permissions``. + denial_condition (google.type.expr_pb2.Expr): + The condition that determines whether this deny rule applies + to a request. If the condition expression evaluates to + ``true``, then the deny rule is applied; otherwise, the deny + rule is not applied. + + Each deny rule is evaluated independently. If this deny rule + does not apply to a request, other deny rules might still + apply. + + The condition can use CEL functions that evaluate `resource + tags `__. + Other functions and operators are not supported. + """ + + denied_principals: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + exception_principals: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + denied_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + exception_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + denial_condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=5, + message=expr_pb2.Expr, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/policy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbcacb68e0609a93b3920cd07db0aa076815584 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2/types/policy.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.iam_v2.types import deny + +__protobuf__ = proto.module( + package="google.iam.v2", + manifest={ + "Policy", + "PolicyRule", + "ListPoliciesRequest", + "ListPoliciesResponse", + "GetPolicyRequest", + "CreatePolicyRequest", + "UpdatePolicyRequest", + "DeletePolicyRequest", + "PolicyOperationMetadata", + }, +) + + +class Policy(proto.Message): + r"""Data for an IAM policy. + + Attributes: + name (str): + Immutable. The resource name of the ``Policy``, which must + be unique. Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + The attachment point is identified by its URL-encoded full + resource name, which means that the forward-slash character, + ``/``, must be written as ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-deny-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, requests can use the + alphanumeric or the numeric ID. Responses always contain the + numeric ID. + uid (str): + Immutable. The globally unique ID of the ``Policy``. + Assigned automatically when the ``Policy`` is created. + kind (str): + Output only. The kind of the ``Policy``. Always contains the + value ``DenyPolicy``. + display_name (str): + A user-specified description of the ``Policy``. This value + can be up to 63 characters. + annotations (MutableMapping[str, str]): + A key-value map to store arbitrary metadata for the + ``Policy``. Keys can be up to 63 characters. Values can be + up to 255 characters. + etag (str): + An opaque tag that identifies the current version of the + ``Policy``. IAM uses this value to help manage concurrent + updates, so they do not cause one update to be overwritten + by another. + + If this field is present in a [CreatePolicy][] request, the + value is ignored. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ``Policy`` was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ``Policy`` was last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ``Policy`` was deleted. Empty + if the policy is not deleted. + rules (MutableSequence[google.cloud.iam_v2.types.PolicyRule]): + A list of rules that specify the behavior of the ``Policy``. + All of the rules should be of the ``kind`` specified in the + ``Policy``. + managing_authority (str): + Immutable. Specifies that this policy is + managed by an authority and can only be modified + by that authority. Usage is restricted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + kind: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + rules: MutableSequence["PolicyRule"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="PolicyRule", + ) + managing_authority: str = proto.Field( + proto.STRING, + number=11, + ) + + +class PolicyRule(proto.Message): + r"""A single rule in a ``Policy``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + deny_rule (google.cloud.iam_v2.types.DenyRule): + A rule for a deny policy. + + This field is a member of `oneof`_ ``kind``. + description (str): + A user-specified description of the rule. + This value can be up to 256 characters. + """ + + deny_rule: deny.DenyRule = proto.Field( + proto.MESSAGE, + number=2, + oneof="kind", + message=deny.DenyRule, + ) + description: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPoliciesRequest(proto.Message): + r"""Request message for ``ListPolicies``. + + Attributes: + parent (str): + Required. The resource that the policy is attached to, along + with the kind of policy to list. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded full + resource name, which means that the forward-slash character, + ``/``, must be written as ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + page_size (int): + The maximum number of policies to return. IAM + ignores this value and uses the value 1000. + page_token (str): + A page token received in a + [ListPoliciesResponse][google.iam.v2.ListPoliciesResponse]. + Provide this token to retrieve the next page. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPoliciesResponse(proto.Message): + r"""Response message for ``ListPolicies``. + + Attributes: + policies (MutableSequence[google.cloud.iam_v2.types.Policy]): + Metadata for the policies that are attached + to the resource. + next_page_token (str): + A page token that you can use in a + [ListPoliciesRequest][google.iam.v2.ListPoliciesRequest] to + retrieve the next page. If this field is omitted, there are + no additional pages. + """ + + @property + def raw_page(self): + return self + + policies: MutableSequence["Policy"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Policy", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPolicyRequest(proto.Message): + r"""Request message for ``GetPolicy``. + + Attributes: + name (str): + Required. The resource name of the policy to retrieve. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that the + forward-slash character, ``/``, must be written as ``%2F``. + For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePolicyRequest(proto.Message): + r"""Request message for ``CreatePolicy``. + + Attributes: + parent (str): + Required. The resource that the policy is attached to, along + with the kind of policy to create. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded full + resource name, which means that the forward-slash character, + ``/``, must be written as ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + policy (google.cloud.iam_v2.types.Policy): + Required. The policy to create. + policy_id (str): + The ID to use for this policy, which will become the final + component of the policy's resource name. The ID must contain + 3 to 63 characters. It can contain lowercase letters and + numbers, as well as dashes (``-``) and periods (``.``). The + first character must be a lowercase letter. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + policy: "Policy" = proto.Field( + proto.MESSAGE, + number=2, + message="Policy", + ) + policy_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdatePolicyRequest(proto.Message): + r"""Request message for ``UpdatePolicy``. + + Attributes: + policy (google.cloud.iam_v2.types.Policy): + Required. The policy to update. + + To prevent conflicting updates, the ``etag`` value must + match the value that is stored in IAM. If the ``etag`` + values do not match, the request fails with a ``409`` error + code and ``ABORTED`` status. + """ + + policy: "Policy" = proto.Field( + proto.MESSAGE, + number=1, + message="Policy", + ) + + +class DeletePolicyRequest(proto.Message): + r"""Request message for ``DeletePolicy``. + + Attributes: + name (str): + Required. The resource name of the policy to delete. Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that the + forward-slash character, ``/``, must be written as ``%2F``. + For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + etag (str): + Optional. The expected ``etag`` of the policy to delete. If + the value does not match the value that is stored in IAM, + the request fails with a ``409`` error code and ``ABORTED`` + status. + + If you omit this field, the policy is deleted regardless of + its current ``etag``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PolicyOperationMetadata(proto.Message): + r"""Metadata for long-running ``Policy`` operations. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the ``google.longrunning.Operation`` was + created. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3776318f20c5430b07ad8059949188b9992287c0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/__init__.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.iam_v2beta import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.policies import PoliciesAsyncClient, PoliciesClient +from .types.deny import DenyRule +from .types.policy import ( + CreatePolicyRequest, + DeletePolicyRequest, + GetPolicyRequest, + ListPoliciesRequest, + ListPoliciesResponse, + Policy, + PolicyOperationMetadata, + PolicyRule, + UpdatePolicyRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.iam_v2beta") # type: ignore + api_core.check_dependency_versions("google.cloud.iam_v2beta") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.iam_v2beta" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "PoliciesAsyncClient", + "CreatePolicyRequest", + "DeletePolicyRequest", + "DenyRule", + "GetPolicyRequest", + "ListPoliciesRequest", + "ListPoliciesResponse", + "PoliciesClient", + "Policy", + "PolicyOperationMetadata", + "PolicyRule", + "UpdatePolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1cd3fb1c10ae2753e88116cb0c2cd02479c40588 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_v2beta", + "protoPackage": "google.iam.v2beta", + "schema": "1.0", + "services": { + "Policies": { + "clients": { + "grpc": { + "libraryClient": "PoliciesClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PoliciesAsyncClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a031b8d466972f8e0b3509ee43a1d166d4c3df2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PoliciesAsyncClient +from .client import PoliciesClient + +__all__ = ( + "PoliciesClient", + "PoliciesAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ad02c6fa19ea45539d24a52f4a6ee696753ed266 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/async_client.py @@ -0,0 +1,1031 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v2beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v2beta.services.policies import pagers +from google.cloud.iam_v2beta.types import policy +from google.cloud.iam_v2beta.types import policy as gi_policy + +from .client import PoliciesClient +from .transports.base import DEFAULT_CLIENT_INFO, PoliciesTransport +from .transports.grpc_asyncio import PoliciesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PoliciesAsyncClient: + """An interface for managing Identity and Access Management + (IAM) policies. + """ + + _client: PoliciesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PoliciesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PoliciesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PoliciesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PoliciesClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod( + PoliciesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PoliciesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(PoliciesClient.common_folder_path) + parse_common_folder_path = staticmethod(PoliciesClient.parse_common_folder_path) + common_organization_path = staticmethod(PoliciesClient.common_organization_path) + parse_common_organization_path = staticmethod( + PoliciesClient.parse_common_organization_path + ) + common_project_path = staticmethod(PoliciesClient.common_project_path) + parse_common_project_path = staticmethod(PoliciesClient.parse_common_project_path) + common_location_path = staticmethod(PoliciesClient.common_location_path) + parse_common_location_path = staticmethod(PoliciesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesAsyncClient: The constructed client. + """ + sa_info_func = ( + PoliciesClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(PoliciesAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesAsyncClient: The constructed client. + """ + sa_file_func = ( + PoliciesClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(PoliciesAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PoliciesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PoliciesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PoliciesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PoliciesTransport, Callable[..., PoliciesTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policies async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PoliciesTransport,Callable[..., PoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PoliciesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v2beta.PoliciesAsyncClient`.", + extra={ + "serviceName": "google.iam.v2beta.Policies", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.v2beta.Policies", + "credentialsType": None, + }, + ) + + async def list_policies( + self, + request: Optional[Union[policy.ListPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPoliciesAsyncPager: + r"""Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + async def sample_list_policies(): + # Create a client + client = iam_v2beta.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2beta.ListPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2beta.types.ListPoliciesRequest, dict]]): + The request object. Request message for ``ListPolicies``. + parent (:class:`str`): + Required. The resource that the policy is attached to, + along with the kind of policy to list. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2beta.services.policies.pagers.ListPoliciesAsyncPager: + Response message for ListPolicies. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.ListPoliciesRequest): + request = policy.ListPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_policy( + self, + request: Optional[Union[policy.GetPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy.Policy: + r"""Gets a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + async def sample_get_policy(): + # Create a client + client = iam_v2beta.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2beta.GetPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2beta.types.GetPolicyRequest, dict]]): + The request object. Request message for ``GetPolicy``. + name (:class:`str`): + Required. The resource name of the policy to retrieve. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2beta.types.Policy: + Data for an IAM policy. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.GetPolicyRequest): + request = policy.GetPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_policy( + self, + request: Optional[Union[gi_policy.CreatePolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + policy: Optional[gi_policy.Policy] = None, + policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + async def sample_create_policy(): + # Create a client + client = iam_v2beta.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2beta.CreatePolicyRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2beta.types.CreatePolicyRequest, dict]]): + The request object. Request message for ``CreatePolicy``. + parent (:class:`str`): + Required. The resource that the policy is attached to, + along with the kind of policy to create. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy (:class:`google.cloud.iam_v2beta.types.Policy`): + Required. The policy to create. + This corresponds to the ``policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_id (:class:`str`): + The ID to use for this policy, which will become the + final component of the policy's resource name. The ID + must contain 3 to 63 characters. It can contain + lowercase letters and numbers, as well as dashes (``-``) + and periods (``.``). The first character must be a + lowercase letter. + + This corresponds to the ``policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2beta.types.Policy` Data for + an IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy, policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gi_policy.CreatePolicyRequest): + request = gi_policy.CreatePolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy is not None: + request.policy = policy + if policy_id is not None: + request.policy_id = policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gi_policy.Policy, + metadata_type=gi_policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_policy( + self, + request: Optional[Union[policy.UpdatePolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2beta.Policies.GetPolicy] to read + the current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + async def sample_update_policy(): + # Create a client + client = iam_v2beta.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2beta.UpdatePolicyRequest( + ) + + # Make the request + operation = client.update_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2beta.types.UpdatePolicyRequest, dict]]): + The request object. Request message for ``UpdatePolicy``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2beta.types.Policy` Data for + an IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.UpdatePolicyRequest): + request = policy.UpdatePolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy.name", request.policy.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_policy( + self, + request: Optional[Union[policy.DeletePolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a policy. This action is permanent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + async def sample_delete_policy(): + # Create a client + client = iam_v2beta.PoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v2beta.DeletePolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v2beta.types.DeletePolicyRequest, dict]]): + The request object. Request message for ``DeletePolicy``. + name (:class:`str`): + Required. The resource name of the policy to delete. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2beta.types.Policy` Data for + an IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.DeletePolicyRequest): + request = policy.DeletePolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PoliciesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PoliciesAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/client.py new file mode 100644 index 0000000000000000000000000000000000000000..ad98836be96d10be02b8791b74871cbc8ca2d743 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/client.py @@ -0,0 +1,1444 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v2beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v2beta.services.policies import pagers +from google.cloud.iam_v2beta.types import policy +from google.cloud.iam_v2beta.types import policy as gi_policy + +from .transports.base import DEFAULT_CLIENT_INFO, PoliciesTransport +from .transports.grpc import PoliciesGrpcTransport +from .transports.grpc_asyncio import PoliciesGrpcAsyncIOTransport + + +class PoliciesClientMeta(type): + """Metaclass for the Policies client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PoliciesTransport]] + _transport_registry["grpc"] = PoliciesGrpcTransport + _transport_registry["grpc_asyncio"] = PoliciesGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PoliciesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PoliciesClient(metaclass=PoliciesClientMeta): + """An interface for managing Identity and Access Management + (IAM) policies. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PoliciesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = PoliciesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = PoliciesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PoliciesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PoliciesTransport, Callable[..., PoliciesTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policies client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PoliciesTransport,Callable[..., PoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PoliciesClient._read_environment_variables() + ) + self._client_cert_source = PoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, PoliciesTransport) + if transport_provided: + # transport is a PoliciesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or PoliciesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PoliciesTransport], Callable[..., PoliciesTransport] + ] = ( + PoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PoliciesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v2beta.PoliciesClient`.", + extra={ + "serviceName": "google.iam.v2beta.Policies", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.v2beta.Policies", + "credentialsType": None, + }, + ) + + def list_policies( + self, + request: Optional[Union[policy.ListPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPoliciesPager: + r"""Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + def sample_list_policies(): + # Create a client + client = iam_v2beta.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2beta.ListPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v2beta.types.ListPoliciesRequest, dict]): + The request object. Request message for ``ListPolicies``. + parent (str): + Required. The resource that the policy is attached to, + along with the kind of policy to list. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2beta.services.policies.pagers.ListPoliciesPager: + Response message for ListPolicies. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.ListPoliciesRequest): + request = policy.ListPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_policy( + self, + request: Optional[Union[policy.GetPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy.Policy: + r"""Gets a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + def sample_get_policy(): + # Create a client + client = iam_v2beta.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2beta.GetPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2beta.types.GetPolicyRequest, dict]): + The request object. Request message for ``GetPolicy``. + name (str): + Required. The resource name of the policy to retrieve. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v2beta.types.Policy: + Data for an IAM policy. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.GetPolicyRequest): + request = policy.GetPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_policy( + self, + request: Optional[Union[gi_policy.CreatePolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + policy: Optional[gi_policy.Policy] = None, + policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + def sample_create_policy(): + # Create a client + client = iam_v2beta.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2beta.CreatePolicyRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2beta.types.CreatePolicyRequest, dict]): + The request object. Request message for ``CreatePolicy``. + parent (str): + Required. The resource that the policy is attached to, + along with the kind of policy to create. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded + full resource name, which means that the forward-slash + character, ``/``, must be written as ``%2F``. For + example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy (google.cloud.iam_v2beta.types.Policy): + Required. The policy to create. + This corresponds to the ``policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_id (str): + The ID to use for this policy, which will become the + final component of the policy's resource name. The ID + must contain 3 to 63 characters. It can contain + lowercase letters and numbers, as well as dashes (``-``) + and periods (``.``). The first character must be a + lowercase letter. + + This corresponds to the ``policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2beta.types.Policy` Data for + an IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy, policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gi_policy.CreatePolicyRequest): + request = gi_policy.CreatePolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy is not None: + request.policy = policy + if policy_id is not None: + request.policy_id = policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gi_policy.Policy, + metadata_type=gi_policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + def update_policy( + self, + request: Optional[Union[policy.UpdatePolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2beta.Policies.GetPolicy] to read + the current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + def sample_update_policy(): + # Create a client + client = iam_v2beta.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2beta.UpdatePolicyRequest( + ) + + # Make the request + operation = client.update_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2beta.types.UpdatePolicyRequest, dict]): + The request object. Request message for ``UpdatePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2beta.types.Policy` Data for + an IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.UpdatePolicyRequest): + request = policy.UpdatePolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy.name", request.policy.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + def delete_policy( + self, + request: Optional[Union[policy.DeletePolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a policy. This action is permanent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v2beta + + def sample_delete_policy(): + # Create a client + client = iam_v2beta.PoliciesClient() + + # Initialize request argument(s) + request = iam_v2beta.DeletePolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v2beta.types.DeletePolicyRequest, dict]): + The request object. Request message for ``DeletePolicy``. + name (str): + Required. The resource name of the policy to delete. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that + the forward-slash character, ``/``, must be written as + ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v2beta.types.Policy` Data for + an IAM policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy.DeletePolicyRequest): + request = policy.DeletePolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy.Policy, + metadata_type=policy.PolicyOperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PoliciesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PoliciesClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..0375f8c4fb4276f8d59f83b716d898e251852d33 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_v2beta.types import policy + + +class ListPoliciesPager: + """A pager for iterating through ``list_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v2beta.types.ListPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicies`` requests and continue to iterate + through the ``policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v2beta.types.ListPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., policy.ListPoliciesResponse], + request: policy.ListPoliciesRequest, + response: policy.ListPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v2beta.types.ListPoliciesRequest): + The initial request object. + response (google.cloud.iam_v2beta.types.ListPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy.ListPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policy.ListPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy.Policy]: + for page in self.pages: + yield from page.policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPoliciesAsyncPager: + """A pager for iterating through ``list_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v2beta.types.ListPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicies`` requests and continue to iterate + through the ``policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v2beta.types.ListPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[policy.ListPoliciesResponse]], + request: policy.ListPoliciesRequest, + response: policy.ListPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v2beta.types.ListPoliciesRequest): + The initial request object. + response (google.cloud.iam_v2beta.types.ListPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy.ListPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[policy.ListPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy.Policy]: + async def async_generator(): + async for page in self.pages: + for response in page.policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d23dfb5a49532f59e047f3977960837d8d306eaa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PoliciesTransport +from .grpc import PoliciesGrpcTransport +from .grpc_asyncio import PoliciesGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PoliciesTransport]] +_transport_registry["grpc"] = PoliciesGrpcTransport +_transport_registry["grpc_asyncio"] = PoliciesGrpcAsyncIOTransport + +__all__ = ( + "PoliciesTransport", + "PoliciesGrpcTransport", + "PoliciesGrpcAsyncIOTransport", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1e86a2cf7045b419ba0305dfa144d6fd040d2dc2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/base.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v2beta import gapic_version as package_version +from google.cloud.iam_v2beta.types import policy +from google.cloud.iam_v2beta.types import policy as gi_policy + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PoliciesTransport(abc.ABC): + """Abstract transport class for Policies.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_policies: gapic_v1.method.wrap_method( + self.list_policies, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_policy: gapic_v1.method.wrap_method( + self.get_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_policy: gapic_v1.method.wrap_method( + self.create_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy: gapic_v1.method.wrap_method( + self.update_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_policy: gapic_v1.method.wrap_method( + self.delete_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_policies( + self, + ) -> Callable[ + [policy.ListPoliciesRequest], + Union[policy.ListPoliciesResponse, Awaitable[policy.ListPoliciesResponse]], + ]: + raise NotImplementedError() + + @property + def get_policy( + self, + ) -> Callable[ + [policy.GetPolicyRequest], Union[policy.Policy, Awaitable[policy.Policy]] + ]: + raise NotImplementedError() + + @property + def create_policy( + self, + ) -> Callable[ + [gi_policy.CreatePolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_policy( + self, + ) -> Callable[ + [policy.UpdatePolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_policy( + self, + ) -> Callable[ + [policy.DeletePolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PoliciesTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..78c12b678db075e0901d0440312933fb03d25363 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/grpc.py @@ -0,0 +1,517 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_v2beta.types import policy +from google.cloud.iam_v2beta.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO, PoliciesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v2beta.Policies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v2beta.Policies", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PoliciesGrpcTransport(PoliciesTransport): + """gRPC backend transport for Policies. + + An interface for managing Identity and Access Management + (IAM) policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_policies( + self, + ) -> Callable[[policy.ListPoliciesRequest], policy.ListPoliciesResponse]: + r"""Return a callable for the list policies method over gRPC. + + Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + Returns: + Callable[[~.ListPoliciesRequest], + ~.ListPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policies" not in self._stubs: + self._stubs["list_policies"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/ListPolicies", + request_serializer=policy.ListPoliciesRequest.serialize, + response_deserializer=policy.ListPoliciesResponse.deserialize, + ) + return self._stubs["list_policies"] + + @property + def get_policy(self) -> Callable[[policy.GetPolicyRequest], policy.Policy]: + r"""Return a callable for the get policy method over gRPC. + + Gets a policy. + + Returns: + Callable[[~.GetPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy" not in self._stubs: + self._stubs["get_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/GetPolicy", + request_serializer=policy.GetPolicyRequest.serialize, + response_deserializer=policy.Policy.deserialize, + ) + return self._stubs["get_policy"] + + @property + def create_policy( + self, + ) -> Callable[[gi_policy.CreatePolicyRequest], operations_pb2.Operation]: + r"""Return a callable for the create policy method over gRPC. + + Creates a policy. + + Returns: + Callable[[~.CreatePolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy" not in self._stubs: + self._stubs["create_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/CreatePolicy", + request_serializer=gi_policy.CreatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy"] + + @property + def update_policy( + self, + ) -> Callable[[policy.UpdatePolicyRequest], operations_pb2.Operation]: + r"""Return a callable for the update policy method over gRPC. + + Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2beta.Policies.GetPolicy] to read + the current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + Returns: + Callable[[~.UpdatePolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy" not in self._stubs: + self._stubs["update_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/UpdatePolicy", + request_serializer=policy.UpdatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy"] + + @property + def delete_policy( + self, + ) -> Callable[[policy.DeletePolicyRequest], operations_pb2.Operation]: + r"""Return a callable for the delete policy method over gRPC. + + Deletes a policy. This action is permanent. + + Returns: + Callable[[~.DeletePolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy" not in self._stubs: + self._stubs["delete_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/DeletePolicy", + request_serializer=policy.DeletePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PoliciesGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..f035c4bee1ff6c28bcf85519dc1600f9d38d46d0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/services/policies/transports/grpc_asyncio.py @@ -0,0 +1,612 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_v2beta.types import policy +from google.cloud.iam_v2beta.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO, PoliciesTransport +from .grpc import PoliciesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v2beta.Policies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v2beta.Policies", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PoliciesGrpcAsyncIOTransport(PoliciesTransport): + """gRPC AsyncIO backend transport for Policies. + + An interface for managing Identity and Access Management + (IAM) policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_policies( + self, + ) -> Callable[[policy.ListPoliciesRequest], Awaitable[policy.ListPoliciesResponse]]: + r"""Return a callable for the list policies method over gRPC. + + Retrieves the policies of the specified kind that are + attached to a resource. + + The response lists only policy metadata. In particular, + policy rules are omitted. + + Returns: + Callable[[~.ListPoliciesRequest], + Awaitable[~.ListPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policies" not in self._stubs: + self._stubs["list_policies"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/ListPolicies", + request_serializer=policy.ListPoliciesRequest.serialize, + response_deserializer=policy.ListPoliciesResponse.deserialize, + ) + return self._stubs["list_policies"] + + @property + def get_policy( + self, + ) -> Callable[[policy.GetPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get policy method over gRPC. + + Gets a policy. + + Returns: + Callable[[~.GetPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy" not in self._stubs: + self._stubs["get_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/GetPolicy", + request_serializer=policy.GetPolicyRequest.serialize, + response_deserializer=policy.Policy.deserialize, + ) + return self._stubs["get_policy"] + + @property + def create_policy( + self, + ) -> Callable[[gi_policy.CreatePolicyRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create policy method over gRPC. + + Creates a policy. + + Returns: + Callable[[~.CreatePolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy" not in self._stubs: + self._stubs["create_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/CreatePolicy", + request_serializer=gi_policy.CreatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy"] + + @property + def update_policy( + self, + ) -> Callable[[policy.UpdatePolicyRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update policy method over gRPC. + + Updates the specified policy. + + You can update only the rules and the display name for the + policy. + + To update a policy, you should use a read-modify-write loop: + + 1. Use [GetPolicy][google.iam.v2beta.Policies.GetPolicy] to read + the current version of the policy. + 2. Modify the policy as needed. + 3. Use ``UpdatePolicy`` to write the updated policy. + + This pattern helps prevent conflicts between concurrent updates. + + Returns: + Callable[[~.UpdatePolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy" not in self._stubs: + self._stubs["update_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/UpdatePolicy", + request_serializer=policy.UpdatePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy"] + + @property + def delete_policy( + self, + ) -> Callable[[policy.DeletePolicyRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete policy method over gRPC. + + Deletes a policy. This action is permanent. + + Returns: + Callable[[~.DeletePolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy" not in self._stubs: + self._stubs["delete_policy"] = self._logged_channel.unary_unary( + "/google.iam.v2beta.Policies/DeletePolicy", + request_serializer=policy.DeletePolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_policies: self._wrap_method( + self.list_policies, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_policy: self._wrap_method( + self.get_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_policy: self._wrap_method( + self.create_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy: self._wrap_method( + self.update_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_policy: self._wrap_method( + self.delete_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("PoliciesGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..995b92b87cc94ecdc1ba3adcc64a3c19abd500cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .deny import ( + DenyRule, +) +from .policy import ( + CreatePolicyRequest, + DeletePolicyRequest, + GetPolicyRequest, + ListPoliciesRequest, + ListPoliciesResponse, + Policy, + PolicyOperationMetadata, + PolicyRule, + UpdatePolicyRequest, +) + +__all__ = ( + "DenyRule", + "CreatePolicyRequest", + "DeletePolicyRequest", + "GetPolicyRequest", + "ListPoliciesRequest", + "ListPoliciesResponse", + "Policy", + "PolicyOperationMetadata", + "PolicyRule", + "UpdatePolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/deny.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/deny.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6688ed6af7a33b10f8ee5407577f40943ee7f9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/deny.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.type.expr_pb2 as expr_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v2beta", + manifest={ + "DenyRule", + }, +) + + +class DenyRule(proto.Message): + r"""A deny rule in an IAM deny policy. + + Attributes: + denied_principals (MutableSequence[str]): + The identities that are prevented from using one or more + permissions on Google Cloud resources. This field can + contain the following values: + + - ``principalSet://goog/public:all``: A special identifier + that represents any principal that is on the internet, + even if they do not have a Google Account or are not + logged in. + + - ``principal://goog/subject/{email_id}``: A specific Google + Account. Includes Gmail, Cloud Identity, and Google + Workspace user accounts. For example, + ``principal://goog/subject/alice@example.com``. + + - ``deleted:principal://goog/subject/{email_id}?uid={uid}``: + A specific Google Account that was deleted recently. For + example, + ``deleted:principal://goog/subject/alice@example.com?uid=1234567890``. + If the Google Account is recovered, this identifier + reverts to the standard identifier for a Google Account. + + - ``principalSet://goog/group/{group_id}``: A Google group. + For example, + ``principalSet://goog/group/admins@example.com``. + + - ``deleted:principalSet://goog/group/{group_id}?uid={uid}``: + A Google group that was deleted recently. For example, + ``deleted:principalSet://goog/group/admins@example.com?uid=1234567890``. + If the Google group is restored, this identifier reverts + to the standard identifier for a Google group. + + - ``principal://iam.googleapis.com/projects/-/serviceAccounts/{service_account_id}``: + A Google Cloud service account. For example, + ``principal://iam.googleapis.com/projects/-/serviceAccounts/my-service-account@iam.gserviceaccount.com``. + + - ``deleted:principal://iam.googleapis.com/projects/-/serviceAccounts/{service_account_id}?uid={uid}``: + A Google Cloud service account that was deleted recently. + For example, + ``deleted:principal://iam.googleapis.com/projects/-/serviceAccounts/my-service-account@iam.gserviceaccount.com?uid=1234567890``. + If the service account is undeleted, this identifier + reverts to the standard identifier for a service account. + + - ``principalSet://goog/cloudIdentityCustomerId/{customer_id}``: + All of the principals associated with the specified Google + Workspace or Cloud Identity customer ID. For example, + ``principalSet://goog/cloudIdentityCustomerId/C01Abc35``. + exception_principals (MutableSequence[str]): + The identities that are excluded from the deny rule, even if + they are listed in the ``denied_principals``. For example, + you could add a Google group to the ``denied_principals``, + then exclude specific users who belong to that group. + + This field can contain the same values as the + ``denied_principals`` field, excluding + ``principalSet://goog/public:all``, which represents all + users on the internet. + denied_permissions (MutableSequence[str]): + The permissions that are explicitly denied by this rule. + Each permission uses the format + ``{service_fqdn}/{resource}.{verb}``, where + ``{service_fqdn}`` is the fully qualified domain name for + the service. For example, ``iam.googleapis.com/roles.list``. + exception_permissions (MutableSequence[str]): + Specifies the permissions that this rule excludes from the + set of denied permissions given by ``denied_permissions``. + If a permission appears in ``denied_permissions`` *and* in + ``exception_permissions`` then it will *not* be denied. + + The excluded permissions can be specified using the same + syntax as ``denied_permissions``. + denial_condition (google.type.expr_pb2.Expr): + The condition that determines whether this deny rule applies + to a request. If the condition expression evaluates to + ``true``, then the deny rule is applied; otherwise, the deny + rule is not applied. + + Each deny rule is evaluated independently. If this deny rule + does not apply to a request, other deny rules might still + apply. + + The condition can use CEL functions that evaluate `resource + tags `__. + Other functions and operators are not supported. + """ + + denied_principals: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + exception_principals: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + denied_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + exception_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + denial_condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=5, + message=expr_pb2.Expr, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/policy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf4537b295ccdc7b999bd0cd28645e069b1cab2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v2beta/types/policy.py @@ -0,0 +1,375 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.iam_v2beta.types import deny + +__protobuf__ = proto.module( + package="google.iam.v2beta", + manifest={ + "Policy", + "PolicyRule", + "ListPoliciesRequest", + "ListPoliciesResponse", + "GetPolicyRequest", + "CreatePolicyRequest", + "UpdatePolicyRequest", + "DeletePolicyRequest", + "PolicyOperationMetadata", + }, +) + + +class Policy(proto.Message): + r"""Data for an IAM policy. + + Attributes: + name (str): + Immutable. The resource name of the ``Policy``, which must + be unique. Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + The attachment point is identified by its URL-encoded full + resource name, which means that the forward-slash character, + ``/``, must be written as ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-deny-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, requests can use the + alphanumeric or the numeric ID. Responses always contain the + numeric ID. + uid (str): + Immutable. The globally unique ID of the ``Policy``. + Assigned automatically when the ``Policy`` is created. + kind (str): + Output only. The kind of the ``Policy``. Always contains the + value ``DenyPolicy``. + display_name (str): + A user-specified description of the ``Policy``. This value + can be up to 63 characters. + annotations (MutableMapping[str, str]): + A key-value map to store arbitrary metadata for the + ``Policy``. Keys can be up to 63 characters. Values can be + up to 255 characters. + etag (str): + An opaque tag that identifies the current version of the + ``Policy``. IAM uses this value to help manage concurrent + updates, so they do not cause one update to be overwritten + by another. + + If this field is present in a [CreatePolicy][] request, the + value is ignored. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ``Policy`` was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ``Policy`` was last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ``Policy`` was deleted. Empty + if the policy is not deleted. + rules (MutableSequence[google.cloud.iam_v2beta.types.PolicyRule]): + A list of rules that specify the behavior of the ``Policy``. + All of the rules should be of the ``kind`` specified in the + ``Policy``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + kind: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + rules: MutableSequence["PolicyRule"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="PolicyRule", + ) + + +class PolicyRule(proto.Message): + r"""A single rule in a ``Policy``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + deny_rule (google.cloud.iam_v2beta.types.DenyRule): + A rule for a deny policy. + + This field is a member of `oneof`_ ``kind``. + description (str): + A user-specified description of the rule. + This value can be up to 256 characters. + """ + + deny_rule: deny.DenyRule = proto.Field( + proto.MESSAGE, + number=2, + oneof="kind", + message=deny.DenyRule, + ) + description: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPoliciesRequest(proto.Message): + r"""Request message for ``ListPolicies``. + + Attributes: + parent (str): + Required. The resource that the policy is attached to, along + with the kind of policy to list. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded full + resource name, which means that the forward-slash character, + ``/``, must be written as ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + page_size (int): + The maximum number of policies to return. IAM + ignores this value and uses the value 1000. + page_token (str): + A page token received in a + [ListPoliciesResponse][google.iam.v2beta.ListPoliciesResponse]. + Provide this token to retrieve the next page. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPoliciesResponse(proto.Message): + r"""Response message for ``ListPolicies``. + + Attributes: + policies (MutableSequence[google.cloud.iam_v2beta.types.Policy]): + Metadata for the policies that are attached + to the resource. + next_page_token (str): + A page token that you can use in a + [ListPoliciesRequest][google.iam.v2beta.ListPoliciesRequest] + to retrieve the next page. If this field is omitted, there + are no additional pages. + """ + + @property + def raw_page(self): + return self + + policies: MutableSequence["Policy"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Policy", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPolicyRequest(proto.Message): + r"""Request message for ``GetPolicy``. + + Attributes: + name (str): + Required. The resource name of the policy to retrieve. + Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that the + forward-slash character, ``/``, must be written as ``%2F``. + For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePolicyRequest(proto.Message): + r"""Request message for ``CreatePolicy``. + + Attributes: + parent (str): + Required. The resource that the policy is attached to, along + with the kind of policy to create. Format: + ``policies/{attachment_point}/denypolicies`` + + The attachment point is identified by its URL-encoded full + resource name, which means that the forward-slash character, + ``/``, must be written as ``%2F``. For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + policy (google.cloud.iam_v2beta.types.Policy): + Required. The policy to create. + policy_id (str): + The ID to use for this policy, which will become the final + component of the policy's resource name. The ID must contain + 3 to 63 characters. It can contain lowercase letters and + numbers, as well as dashes (``-``) and periods (``.``). The + first character must be a lowercase letter. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + policy: "Policy" = proto.Field( + proto.MESSAGE, + number=2, + message="Policy", + ) + policy_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdatePolicyRequest(proto.Message): + r"""Request message for ``UpdatePolicy``. + + Attributes: + policy (google.cloud.iam_v2beta.types.Policy): + Required. The policy to update. + + To prevent conflicting updates, the ``etag`` value must + match the value that is stored in IAM. If the ``etag`` + values do not match, the request fails with a ``409`` error + code and ``ABORTED`` status. + """ + + policy: "Policy" = proto.Field( + proto.MESSAGE, + number=1, + message="Policy", + ) + + +class DeletePolicyRequest(proto.Message): + r"""Request message for ``DeletePolicy``. + + Attributes: + name (str): + Required. The resource name of the policy to delete. Format: + ``policies/{attachment_point}/denypolicies/{policy_id}`` + + Use the URL-encoded full resource name, which means that the + forward-slash character, ``/``, must be written as ``%2F``. + For example, + ``policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy``. + + For organizations and folders, use the numeric ID in the + full resource name. For projects, you can use the + alphanumeric or the numeric ID. + etag (str): + Optional. The expected ``etag`` of the policy to delete. If + the value does not match the value that is stored in IAM, + the request fails with a ``409`` error code and ``ABORTED`` + status. + + If you omit this field, the policy is deleted regardless of + its current ``etag``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PolicyOperationMetadata(proto.Message): + r"""Metadata for long-running ``Policy`` operations. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the ``google.longrunning.Operation`` was + created. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea1969e25a1624bdc6f92f1cd0a54d332ff9d45 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/__init__.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.iam_v3 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.policy_bindings import PolicyBindingsAsyncClient, PolicyBindingsClient +from .services.principal_access_boundary_policies import ( + PrincipalAccessBoundaryPoliciesAsyncClient, + PrincipalAccessBoundaryPoliciesClient, +) +from .types.operation_metadata import OperationMetadata +from .types.policy_binding_resources import PolicyBinding +from .types.policy_bindings_service import ( + CreatePolicyBindingRequest, + DeletePolicyBindingRequest, + GetPolicyBindingRequest, + ListPolicyBindingsRequest, + ListPolicyBindingsResponse, + SearchTargetPolicyBindingsRequest, + SearchTargetPolicyBindingsResponse, + UpdatePolicyBindingRequest, +) +from .types.principal_access_boundary_policies_service import ( + CreatePrincipalAccessBoundaryPolicyRequest, + DeletePrincipalAccessBoundaryPolicyRequest, + GetPrincipalAccessBoundaryPolicyRequest, + ListPrincipalAccessBoundaryPoliciesRequest, + ListPrincipalAccessBoundaryPoliciesResponse, + SearchPrincipalAccessBoundaryPolicyBindingsRequest, + SearchPrincipalAccessBoundaryPolicyBindingsResponse, + UpdatePrincipalAccessBoundaryPolicyRequest, +) +from .types.principal_access_boundary_policy_resources import ( + PrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPolicyDetails, + PrincipalAccessBoundaryPolicyRule, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.iam_v3") # type: ignore + api_core.check_dependency_versions("google.cloud.iam_v3") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.iam_v3" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "PolicyBindingsAsyncClient", + "PrincipalAccessBoundaryPoliciesAsyncClient", + "CreatePolicyBindingRequest", + "CreatePrincipalAccessBoundaryPolicyRequest", + "DeletePolicyBindingRequest", + "DeletePrincipalAccessBoundaryPolicyRequest", + "GetPolicyBindingRequest", + "GetPrincipalAccessBoundaryPolicyRequest", + "ListPolicyBindingsRequest", + "ListPolicyBindingsResponse", + "ListPrincipalAccessBoundaryPoliciesRequest", + "ListPrincipalAccessBoundaryPoliciesResponse", + "OperationMetadata", + "PolicyBinding", + "PolicyBindingsClient", + "PrincipalAccessBoundaryPoliciesClient", + "PrincipalAccessBoundaryPolicy", + "PrincipalAccessBoundaryPolicyDetails", + "PrincipalAccessBoundaryPolicyRule", + "SearchPrincipalAccessBoundaryPolicyBindingsRequest", + "SearchPrincipalAccessBoundaryPolicyBindingsResponse", + "SearchTargetPolicyBindingsRequest", + "SearchTargetPolicyBindingsResponse", + "UpdatePolicyBindingRequest", + "UpdatePrincipalAccessBoundaryPolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..0a2fe83852d756d25a9f3771a314ba22e163bf99 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/gapic_metadata.json @@ -0,0 +1,227 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_v3", + "protoPackage": "google.iam.v3", + "schema": "1.0", + "services": { + "PolicyBindings": { + "clients": { + "grpc": { + "libraryClient": "PolicyBindingsClient", + "rpcs": { + "CreatePolicyBinding": { + "methods": [ + "create_policy_binding" + ] + }, + "DeletePolicyBinding": { + "methods": [ + "delete_policy_binding" + ] + }, + "GetPolicyBinding": { + "methods": [ + "get_policy_binding" + ] + }, + "ListPolicyBindings": { + "methods": [ + "list_policy_bindings" + ] + }, + "SearchTargetPolicyBindings": { + "methods": [ + "search_target_policy_bindings" + ] + }, + "UpdatePolicyBinding": { + "methods": [ + "update_policy_binding" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyBindingsAsyncClient", + "rpcs": { + "CreatePolicyBinding": { + "methods": [ + "create_policy_binding" + ] + }, + "DeletePolicyBinding": { + "methods": [ + "delete_policy_binding" + ] + }, + "GetPolicyBinding": { + "methods": [ + "get_policy_binding" + ] + }, + "ListPolicyBindings": { + "methods": [ + "list_policy_bindings" + ] + }, + "SearchTargetPolicyBindings": { + "methods": [ + "search_target_policy_bindings" + ] + }, + "UpdatePolicyBinding": { + "methods": [ + "update_policy_binding" + ] + } + } + }, + "rest": { + "libraryClient": "PolicyBindingsClient", + "rpcs": { + "CreatePolicyBinding": { + "methods": [ + "create_policy_binding" + ] + }, + "DeletePolicyBinding": { + "methods": [ + "delete_policy_binding" + ] + }, + "GetPolicyBinding": { + "methods": [ + "get_policy_binding" + ] + }, + "ListPolicyBindings": { + "methods": [ + "list_policy_bindings" + ] + }, + "SearchTargetPolicyBindings": { + "methods": [ + "search_target_policy_bindings" + ] + }, + "UpdatePolicyBinding": { + "methods": [ + "update_policy_binding" + ] + } + } + } + } + }, + "PrincipalAccessBoundaryPolicies": { + "clients": { + "grpc": { + "libraryClient": "PrincipalAccessBoundaryPoliciesClient", + "rpcs": { + "CreatePrincipalAccessBoundaryPolicy": { + "methods": [ + "create_principal_access_boundary_policy" + ] + }, + "DeletePrincipalAccessBoundaryPolicy": { + "methods": [ + "delete_principal_access_boundary_policy" + ] + }, + "GetPrincipalAccessBoundaryPolicy": { + "methods": [ + "get_principal_access_boundary_policy" + ] + }, + "ListPrincipalAccessBoundaryPolicies": { + "methods": [ + "list_principal_access_boundary_policies" + ] + }, + "SearchPrincipalAccessBoundaryPolicyBindings": { + "methods": [ + "search_principal_access_boundary_policy_bindings" + ] + }, + "UpdatePrincipalAccessBoundaryPolicy": { + "methods": [ + "update_principal_access_boundary_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PrincipalAccessBoundaryPoliciesAsyncClient", + "rpcs": { + "CreatePrincipalAccessBoundaryPolicy": { + "methods": [ + "create_principal_access_boundary_policy" + ] + }, + "DeletePrincipalAccessBoundaryPolicy": { + "methods": [ + "delete_principal_access_boundary_policy" + ] + }, + "GetPrincipalAccessBoundaryPolicy": { + "methods": [ + "get_principal_access_boundary_policy" + ] + }, + "ListPrincipalAccessBoundaryPolicies": { + "methods": [ + "list_principal_access_boundary_policies" + ] + }, + "SearchPrincipalAccessBoundaryPolicyBindings": { + "methods": [ + "search_principal_access_boundary_policy_bindings" + ] + }, + "UpdatePrincipalAccessBoundaryPolicy": { + "methods": [ + "update_principal_access_boundary_policy" + ] + } + } + }, + "rest": { + "libraryClient": "PrincipalAccessBoundaryPoliciesClient", + "rpcs": { + "CreatePrincipalAccessBoundaryPolicy": { + "methods": [ + "create_principal_access_boundary_policy" + ] + }, + "DeletePrincipalAccessBoundaryPolicy": { + "methods": [ + "delete_principal_access_boundary_policy" + ] + }, + "GetPrincipalAccessBoundaryPolicy": { + "methods": [ + "get_principal_access_boundary_policy" + ] + }, + "ListPrincipalAccessBoundaryPolicies": { + "methods": [ + "list_principal_access_boundary_policies" + ] + }, + "SearchPrincipalAccessBoundaryPolicyBindings": { + "methods": [ + "search_principal_access_boundary_policy_bindings" + ] + }, + "UpdatePrincipalAccessBoundaryPolicy": { + "methods": [ + "update_principal_access_boundary_policy" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c244552a39da26a50dfdf4cca9afd4cf71323e5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PolicyBindingsAsyncClient +from .client import PolicyBindingsClient + +__all__ = ( + "PolicyBindingsClient", + "PolicyBindingsAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..28fcd3139ab99738c6706dd0db9b1c5e989260d8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/async_client.py @@ -0,0 +1,1266 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3.services.policy_bindings import pagers +from google.cloud.iam_v3.types import ( + operation_metadata, + policy_binding_resources, + policy_bindings_service, +) + +from .client import PolicyBindingsClient +from .transports.base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport +from .transports.grpc_asyncio import PolicyBindingsGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PolicyBindingsAsyncClient: + """An interface for managing Identity and Access Management + (IAM) policy bindings. + """ + + _client: PolicyBindingsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PolicyBindingsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyBindingsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PolicyBindingsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PolicyBindingsClient._DEFAULT_UNIVERSE + + policy_binding_path = staticmethod(PolicyBindingsClient.policy_binding_path) + parse_policy_binding_path = staticmethod( + PolicyBindingsClient.parse_policy_binding_path + ) + common_billing_account_path = staticmethod( + PolicyBindingsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PolicyBindingsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(PolicyBindingsClient.common_folder_path) + parse_common_folder_path = staticmethod( + PolicyBindingsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + PolicyBindingsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + PolicyBindingsClient.parse_common_organization_path + ) + common_project_path = staticmethod(PolicyBindingsClient.common_project_path) + parse_common_project_path = staticmethod( + PolicyBindingsClient.parse_common_project_path + ) + common_location_path = staticmethod(PolicyBindingsClient.common_location_path) + parse_common_location_path = staticmethod( + PolicyBindingsClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsAsyncClient: The constructed client. + """ + sa_info_func = ( + PolicyBindingsClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(PolicyBindingsAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsAsyncClient: The constructed client. + """ + sa_file_func = ( + PolicyBindingsClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(PolicyBindingsAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PolicyBindingsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PolicyBindingsTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyBindingsTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PolicyBindingsClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PolicyBindingsTransport, Callable[..., PolicyBindingsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy bindings async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PolicyBindingsTransport,Callable[..., PolicyBindingsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PolicyBindingsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PolicyBindingsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3.PolicyBindingsAsyncClient`.", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.v3.PolicyBindings", + "credentialsType": None, + }, + ) + + async def create_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.CreatePolicyBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + policy_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_create_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + policy_binding = iam_v3.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3.CreatePolicyBindingRequest( + parent="parent_value", + policy_binding_id="policy_binding_id_value", + policy_binding=policy_binding, + ) + + # Make the request + operation = client.create_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.CreatePolicyBindingRequest, dict]]): + The request object. Request message for + CreatePolicyBinding method. + parent (:class:`str`): + Required. The parent resource where this policy binding + will be created. The binding parent is the closest + Resource Manager resource (project, folder or + organization) to the binding target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding (:class:`google.cloud.iam_v3.types.PolicyBinding`): + Required. The policy binding to + create. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding_id (:class:`str`): + Required. The ID to use for the policy binding, which + will become the final component of the policy binding's + resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``policy_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy_binding, policy_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.CreatePolicyBindingRequest): + request = policy_bindings_service.CreatePolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_binding is not None: + request.policy_binding = policy_binding + if policy_binding_id is not None: + request.policy_binding_id = policy_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.GetPolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_binding_resources.PolicyBinding: + r"""Gets a policy binding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_get_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3.GetPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.GetPolicyBindingRequest, dict]]): + The request object. Request message for GetPolicyBinding + method. + name (:class:`str`): + Required. The name of the policy binding to retrieve. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.types.PolicyBinding: + IAM policy binding resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.GetPolicyBindingRequest): + request = policy_bindings_service.GetPolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.UpdatePolicyBindingRequest, dict] + ] = None, + *, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_update_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + policy_binding = iam_v3.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3.UpdatePolicyBindingRequest( + policy_binding=policy_binding, + ) + + # Make the request + operation = client.update_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.UpdatePolicyBindingRequest, dict]]): + The request object. Request message for + UpdatePolicyBinding method. + policy_binding (:class:`google.cloud.iam_v3.types.PolicyBinding`): + Required. The policy binding to update. + + The policy binding's ``name`` field is used to identify + the policy binding to update. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [policy_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.UpdatePolicyBindingRequest): + request = policy_bindings_service.UpdatePolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_binding is not None: + request.policy_binding = policy_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy_binding.name", request.policy_binding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.DeletePolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_delete_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3.DeletePolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.DeletePolicyBindingRequest, dict]]): + The request object. Request message for + DeletePolicyBinding method. + name (:class:`str`): + Required. The name of the policy binding to delete. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.DeletePolicyBindingRequest): + request = policy_bindings_service.DeletePolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.ListPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPolicyBindingsAsyncPager: + r"""Lists policy bindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_list_policy_bindings(): + # Create a client + client = iam_v3.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3.ListPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.ListPolicyBindingsRequest, dict]]): + The request object. Request message for + ListPolicyBindings method. + parent (:class:`str`): + Required. The parent resource, which owns the collection + of policy bindings. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.policy_bindings.pagers.ListPolicyBindingsAsyncPager: + Response message for + ListPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.ListPolicyBindingsRequest): + request = policy_bindings_service.ListPolicyBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_target_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.SearchTargetPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + target: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchTargetPolicyBindingsAsyncPager: + r"""Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_search_target_policy_bindings(): + # Create a client + client = iam_v3.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3.SearchTargetPolicyBindingsRequest( + target="target_value", + parent="parent_value", + ) + + # Make the request + page_result = client.search_target_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.SearchTargetPolicyBindingsRequest, dict]]): + The request object. Request message for + SearchTargetPolicyBindings method. + parent (:class:`str`): + Required. The parent resource where this search will be + performed. This should be the nearest Resource Manager + resource (project, folder, or organization) to the + target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target (:class:`str`): + Required. The target resource, which is bound to the + policy in the binding. + + Format: + + - ``//iam.googleapis.com/locations/global/workforcePools/POOL_ID`` + - ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID`` + - ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + - ``//cloudresourcemanager.googleapis.com/projects/{project_number}`` + - ``//cloudresourcemanager.googleapis.com/folders/{folder_id}`` + - ``//cloudresourcemanager.googleapis.com/organizations/{organization_id}`` + + This corresponds to the ``target`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.policy_bindings.pagers.SearchTargetPolicyBindingsAsyncPager: + Response message for + SearchTargetPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, target] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, policy_bindings_service.SearchTargetPolicyBindingsRequest + ): + request = policy_bindings_service.SearchTargetPolicyBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if target is not None: + request.target = target + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_target_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchTargetPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PolicyBindingsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PolicyBindingsAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/client.py new file mode 100644 index 0000000000000000000000000000000000000000..4f71e3514abf265e630892743e404f8df3499693 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/client.py @@ -0,0 +1,1692 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3.services.policy_bindings import pagers +from google.cloud.iam_v3.types import ( + operation_metadata, + policy_binding_resources, + policy_bindings_service, +) + +from .transports.base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport +from .transports.grpc import PolicyBindingsGrpcTransport +from .transports.grpc_asyncio import PolicyBindingsGrpcAsyncIOTransport +from .transports.rest import PolicyBindingsRestTransport + + +class PolicyBindingsClientMeta(type): + """Metaclass for the PolicyBindings client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PolicyBindingsTransport]] + _transport_registry["grpc"] = PolicyBindingsGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyBindingsGrpcAsyncIOTransport + _transport_registry["rest"] = PolicyBindingsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PolicyBindingsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PolicyBindingsClient(metaclass=PolicyBindingsClientMeta): + """An interface for managing Identity and Access Management + (IAM) policy bindings. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PolicyBindingsTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyBindingsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def policy_binding_path( + organization: str, + location: str, + policy_binding: str, + ) -> str: + """Returns a fully-qualified policy_binding string.""" + return "organizations/{organization}/locations/{location}/policyBindings/{policy_binding}".format( + organization=organization, + location=location, + policy_binding=policy_binding, + ) + + @staticmethod + def parse_policy_binding_path(path: str) -> Dict[str, str]: + """Parses a policy_binding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/policyBindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = PolicyBindingsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = PolicyBindingsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PolicyBindingsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PolicyBindingsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PolicyBindingsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PolicyBindingsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PolicyBindingsTransport, Callable[..., PolicyBindingsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy bindings client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PolicyBindingsTransport,Callable[..., PolicyBindingsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PolicyBindingsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PolicyBindingsClient._read_environment_variables() + ) + self._client_cert_source = PolicyBindingsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PolicyBindingsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, PolicyBindingsTransport) + if transport_provided: + # transport is a PolicyBindingsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PolicyBindingsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or PolicyBindingsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PolicyBindingsTransport], Callable[..., PolicyBindingsTransport] + ] = ( + PolicyBindingsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PolicyBindingsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3.PolicyBindingsClient`.", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.v3.PolicyBindings", + "credentialsType": None, + }, + ) + + def create_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.CreatePolicyBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + policy_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_create_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsClient() + + # Initialize request argument(s) + policy_binding = iam_v3.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3.CreatePolicyBindingRequest( + parent="parent_value", + policy_binding_id="policy_binding_id_value", + policy_binding=policy_binding, + ) + + # Make the request + operation = client.create_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.CreatePolicyBindingRequest, dict]): + The request object. Request message for + CreatePolicyBinding method. + parent (str): + Required. The parent resource where this policy binding + will be created. The binding parent is the closest + Resource Manager resource (project, folder or + organization) to the binding target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding (google.cloud.iam_v3.types.PolicyBinding): + Required. The policy binding to + create. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding_id (str): + Required. The ID to use for the policy binding, which + will become the final component of the policy binding's + resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``policy_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy_binding, policy_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.CreatePolicyBindingRequest): + request = policy_bindings_service.CreatePolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_binding is not None: + request.policy_binding = policy_binding + if policy_binding_id is not None: + request.policy_binding_id = policy_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.GetPolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_binding_resources.PolicyBinding: + r"""Gets a policy binding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_get_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3.GetPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.GetPolicyBindingRequest, dict]): + The request object. Request message for GetPolicyBinding + method. + name (str): + Required. The name of the policy binding to retrieve. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.types.PolicyBinding: + IAM policy binding resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.GetPolicyBindingRequest): + request = policy_bindings_service.GetPolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.UpdatePolicyBindingRequest, dict] + ] = None, + *, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_update_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsClient() + + # Initialize request argument(s) + policy_binding = iam_v3.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3.UpdatePolicyBindingRequest( + policy_binding=policy_binding, + ) + + # Make the request + operation = client.update_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.UpdatePolicyBindingRequest, dict]): + The request object. Request message for + UpdatePolicyBinding method. + policy_binding (google.cloud.iam_v3.types.PolicyBinding): + Required. The policy binding to update. + + The policy binding's ``name`` field is used to identify + the policy binding to update. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [policy_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.UpdatePolicyBindingRequest): + request = policy_bindings_service.UpdatePolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_binding is not None: + request.policy_binding = policy_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy_binding.name", request.policy_binding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.DeletePolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_delete_policy_binding(): + # Create a client + client = iam_v3.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3.DeletePolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.DeletePolicyBindingRequest, dict]): + The request object. Request message for + DeletePolicyBinding method. + name (str): + Required. The name of the policy binding to delete. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.DeletePolicyBindingRequest): + request = policy_bindings_service.DeletePolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.ListPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPolicyBindingsPager: + r"""Lists policy bindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_list_policy_bindings(): + # Create a client + client = iam_v3.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3.ListPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.ListPolicyBindingsRequest, dict]): + The request object. Request message for + ListPolicyBindings method. + parent (str): + Required. The parent resource, which owns the collection + of policy bindings. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.policy_bindings.pagers.ListPolicyBindingsPager: + Response message for + ListPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.ListPolicyBindingsRequest): + request = policy_bindings_service.ListPolicyBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_policy_bindings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_target_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.SearchTargetPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + target: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchTargetPolicyBindingsPager: + r"""Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_search_target_policy_bindings(): + # Create a client + client = iam_v3.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3.SearchTargetPolicyBindingsRequest( + target="target_value", + parent="parent_value", + ) + + # Make the request + page_result = client.search_target_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.SearchTargetPolicyBindingsRequest, dict]): + The request object. Request message for + SearchTargetPolicyBindings method. + parent (str): + Required. The parent resource where this search will be + performed. This should be the nearest Resource Manager + resource (project, folder, or organization) to the + target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target (str): + Required. The target resource, which is bound to the + policy in the binding. + + Format: + + - ``//iam.googleapis.com/locations/global/workforcePools/POOL_ID`` + - ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID`` + - ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + - ``//cloudresourcemanager.googleapis.com/projects/{project_number}`` + - ``//cloudresourcemanager.googleapis.com/folders/{folder_id}`` + - ``//cloudresourcemanager.googleapis.com/organizations/{organization_id}`` + + This corresponds to the ``target`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.policy_bindings.pagers.SearchTargetPolicyBindingsPager: + Response message for + SearchTargetPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, target] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, policy_bindings_service.SearchTargetPolicyBindingsRequest + ): + request = policy_bindings_service.SearchTargetPolicyBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if target is not None: + request.target = target + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.search_target_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchTargetPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PolicyBindingsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PolicyBindingsClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..7bcf1ad244a91bd887e42207c60e53775b3187ff --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/pagers.py @@ -0,0 +1,369 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_v3.types import policy_binding_resources, policy_bindings_service + + +class ListPolicyBindingsPager: + """A pager for iterating through ``list_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.ListPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.ListPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., policy_bindings_service.ListPolicyBindingsResponse], + request: policy_bindings_service.ListPolicyBindingsRequest, + response: policy_bindings_service.ListPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.ListPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3.types.ListPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.ListPolicyBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policy_bindings_service.ListPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy_binding_resources.PolicyBinding]: + for page in self.pages: + yield from page.policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPolicyBindingsAsyncPager: + """A pager for iterating through ``list_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.ListPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.ListPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[policy_bindings_service.ListPolicyBindingsResponse] + ], + request: policy_bindings_service.ListPolicyBindingsRequest, + response: policy_bindings_service.ListPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.ListPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3.types.ListPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.ListPolicyBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[policy_bindings_service.ListPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy_binding_resources.PolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchTargetPolicyBindingsPager: + """A pager for iterating through ``search_target_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.SearchTargetPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchTargetPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.SearchTargetPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., policy_bindings_service.SearchTargetPolicyBindingsResponse + ], + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + response: policy_bindings_service.SearchTargetPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.SearchTargetPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3.types.SearchTargetPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.SearchTargetPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[policy_bindings_service.SearchTargetPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy_binding_resources.PolicyBinding]: + for page in self.pages: + yield from page.policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchTargetPolicyBindingsAsyncPager: + """A pager for iterating through ``search_target_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.SearchTargetPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchTargetPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.SearchTargetPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[policy_bindings_service.SearchTargetPolicyBindingsResponse] + ], + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + response: policy_bindings_service.SearchTargetPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.SearchTargetPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3.types.SearchTargetPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.SearchTargetPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[policy_bindings_service.SearchTargetPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy_binding_resources.PolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6d5224bc4cc964ac54c8e531309984814978f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PolicyBindingsTransport +from .grpc import PolicyBindingsGrpcTransport +from .grpc_asyncio import PolicyBindingsGrpcAsyncIOTransport +from .rest import PolicyBindingsRestInterceptor, PolicyBindingsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyBindingsTransport]] +_transport_registry["grpc"] = PolicyBindingsGrpcTransport +_transport_registry["grpc_asyncio"] = PolicyBindingsGrpcAsyncIOTransport +_transport_registry["rest"] = PolicyBindingsRestTransport + +__all__ = ( + "PolicyBindingsTransport", + "PolicyBindingsGrpcTransport", + "PolicyBindingsGrpcAsyncIOTransport", + "PolicyBindingsRestTransport", + "PolicyBindingsRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..bd22e891505b8a3043a9aa57818f4822fb02cec3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/base.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3 import gapic_version as package_version +from google.cloud.iam_v3.types import policy_binding_resources, policy_bindings_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PolicyBindingsTransport(abc.ABC): + """Abstract transport class for PolicyBindings.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_policy_binding: gapic_v1.method.wrap_method( + self.create_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.get_policy_binding: gapic_v1.method.wrap_method( + self.get_policy_binding, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy_binding: gapic_v1.method.wrap_method( + self.update_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_policy_binding: gapic_v1.method.wrap_method( + self.delete_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.list_policy_bindings: gapic_v1.method.wrap_method( + self.list_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_target_policy_bindings: gapic_v1.method.wrap_method( + self.search_target_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + Union[ + policy_binding_resources.PolicyBinding, + Awaitable[policy_binding_resources.PolicyBinding], + ], + ]: + raise NotImplementedError() + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + Union[ + policy_bindings_service.ListPolicyBindingsResponse, + Awaitable[policy_bindings_service.ListPolicyBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + Union[ + policy_bindings_service.SearchTargetPolicyBindingsResponse, + Awaitable[policy_bindings_service.SearchTargetPolicyBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PolicyBindingsTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fdc72f349b653dcc980b72b4a8b0c8133ef805 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/grpc.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_v3.types import policy_binding_resources, policy_bindings_service + +from .base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PolicyBindingsGrpcTransport(PolicyBindingsTransport): + """gRPC backend transport for PolicyBindings. + + An interface for managing Identity and Access Management + (IAM) policy bindings. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create policy binding method over gRPC. + + Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + Returns: + Callable[[~.CreatePolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy_binding" not in self._stubs: + self._stubs["create_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/CreatePolicyBinding", + request_serializer=policy_bindings_service.CreatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy_binding"] + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + policy_binding_resources.PolicyBinding, + ]: + r"""Return a callable for the get policy binding method over gRPC. + + Gets a policy binding. + + Returns: + Callable[[~.GetPolicyBindingRequest], + ~.PolicyBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy_binding" not in self._stubs: + self._stubs["get_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/GetPolicyBinding", + request_serializer=policy_bindings_service.GetPolicyBindingRequest.serialize, + response_deserializer=policy_binding_resources.PolicyBinding.deserialize, + ) + return self._stubs["get_policy_binding"] + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update policy binding method over gRPC. + + Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + Returns: + Callable[[~.UpdatePolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy_binding" not in self._stubs: + self._stubs["update_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/UpdatePolicyBinding", + request_serializer=policy_bindings_service.UpdatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy_binding"] + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete policy binding method over gRPC. + + Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + Returns: + Callable[[~.DeletePolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy_binding" not in self._stubs: + self._stubs["delete_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/DeletePolicyBinding", + request_serializer=policy_bindings_service.DeletePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy_binding"] + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + policy_bindings_service.ListPolicyBindingsResponse, + ]: + r"""Return a callable for the list policy bindings method over gRPC. + + Lists policy bindings. + + Returns: + Callable[[~.ListPolicyBindingsRequest], + ~.ListPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policy_bindings" not in self._stubs: + self._stubs["list_policy_bindings"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/ListPolicyBindings", + request_serializer=policy_bindings_service.ListPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.ListPolicyBindingsResponse.deserialize, + ) + return self._stubs["list_policy_bindings"] + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + policy_bindings_service.SearchTargetPolicyBindingsResponse, + ]: + r"""Return a callable for the search target policy bindings method over gRPC. + + Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + Returns: + Callable[[~.SearchTargetPolicyBindingsRequest], + ~.SearchTargetPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_target_policy_bindings" not in self._stubs: + self._stubs["search_target_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/SearchTargetPolicyBindings", + request_serializer=policy_bindings_service.SearchTargetPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.SearchTargetPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_target_policy_bindings"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PolicyBindingsGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6a3ca09b7c16c8428f28ff8437b89ea1dbabb8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/grpc_asyncio.py @@ -0,0 +1,642 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_v3.types import policy_binding_resources, policy_bindings_service + +from .base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport +from .grpc import PolicyBindingsGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PolicyBindingsGrpcAsyncIOTransport(PolicyBindingsTransport): + """gRPC AsyncIO backend transport for PolicyBindings. + + An interface for managing Identity and Access Management + (IAM) policy bindings. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create policy binding method over gRPC. + + Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + Returns: + Callable[[~.CreatePolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy_binding" not in self._stubs: + self._stubs["create_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/CreatePolicyBinding", + request_serializer=policy_bindings_service.CreatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy_binding"] + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + Awaitable[policy_binding_resources.PolicyBinding], + ]: + r"""Return a callable for the get policy binding method over gRPC. + + Gets a policy binding. + + Returns: + Callable[[~.GetPolicyBindingRequest], + Awaitable[~.PolicyBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy_binding" not in self._stubs: + self._stubs["get_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/GetPolicyBinding", + request_serializer=policy_bindings_service.GetPolicyBindingRequest.serialize, + response_deserializer=policy_binding_resources.PolicyBinding.deserialize, + ) + return self._stubs["get_policy_binding"] + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update policy binding method over gRPC. + + Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + Returns: + Callable[[~.UpdatePolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy_binding" not in self._stubs: + self._stubs["update_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/UpdatePolicyBinding", + request_serializer=policy_bindings_service.UpdatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy_binding"] + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete policy binding method over gRPC. + + Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + Returns: + Callable[[~.DeletePolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy_binding" not in self._stubs: + self._stubs["delete_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/DeletePolicyBinding", + request_serializer=policy_bindings_service.DeletePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy_binding"] + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + Awaitable[policy_bindings_service.ListPolicyBindingsResponse], + ]: + r"""Return a callable for the list policy bindings method over gRPC. + + Lists policy bindings. + + Returns: + Callable[[~.ListPolicyBindingsRequest], + Awaitable[~.ListPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policy_bindings" not in self._stubs: + self._stubs["list_policy_bindings"] = self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/ListPolicyBindings", + request_serializer=policy_bindings_service.ListPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.ListPolicyBindingsResponse.deserialize, + ) + return self._stubs["list_policy_bindings"] + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + Awaitable[policy_bindings_service.SearchTargetPolicyBindingsResponse], + ]: + r"""Return a callable for the search target policy bindings method over gRPC. + + Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + Returns: + Callable[[~.SearchTargetPolicyBindingsRequest], + Awaitable[~.SearchTargetPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_target_policy_bindings" not in self._stubs: + self._stubs["search_target_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PolicyBindings/SearchTargetPolicyBindings", + request_serializer=policy_bindings_service.SearchTargetPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.SearchTargetPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_target_policy_bindings"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_policy_binding: self._wrap_method( + self.create_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.get_policy_binding: self._wrap_method( + self.get_policy_binding, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy_binding: self._wrap_method( + self.update_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_policy_binding: self._wrap_method( + self.delete_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.list_policy_bindings: self._wrap_method( + self.list_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_target_policy_bindings: self._wrap_method( + self.search_target_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("PolicyBindingsGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..b385fd6584aafd75b9ca8f55ad6aa18b0475c557 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/rest.py @@ -0,0 +1,1717 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.iam_v3.types import policy_binding_resources, policy_bindings_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePolicyBindingsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PolicyBindingsRestInterceptor: + """Interceptor for PolicyBindings. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PolicyBindingsRestTransport. + + .. code-block:: python + class MyCustomPolicyBindingsInterceptor(PolicyBindingsRestInterceptor): + def pre_create_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_target_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_target_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PolicyBindingsRestTransport(interceptor=MyCustomPolicyBindingsInterceptor()) + client = PolicyBindingsClient(transport=transport) + + + """ + + def pre_create_policy_binding( + self, + request: policy_bindings_service.CreatePolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.CreatePolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_create_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_policy_binding + + DEPRECATED. Please use the `post_create_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_create_policy_binding` interceptor runs + before the `post_create_policy_binding_with_metadata` interceptor. + """ + return response + + def post_create_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_create_policy_binding_with_metadata` + interceptor in new development instead of the `post_create_policy_binding` interceptor. + When both interceptors are used, this `post_create_policy_binding_with_metadata` interceptor runs after the + `post_create_policy_binding` interceptor. The (possibly modified) response returned by + `post_create_policy_binding` will be passed to + `post_create_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_delete_policy_binding( + self, + request: policy_bindings_service.DeletePolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.DeletePolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_delete_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_policy_binding + + DEPRECATED. Please use the `post_delete_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_delete_policy_binding` interceptor runs + before the `post_delete_policy_binding_with_metadata` interceptor. + """ + return response + + def post_delete_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_delete_policy_binding_with_metadata` + interceptor in new development instead of the `post_delete_policy_binding` interceptor. + When both interceptors are used, this `post_delete_policy_binding_with_metadata` interceptor runs after the + `post_delete_policy_binding` interceptor. The (possibly modified) response returned by + `post_delete_policy_binding` will be passed to + `post_delete_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_get_policy_binding( + self, + request: policy_bindings_service.GetPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.GetPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_get_policy_binding( + self, response: policy_binding_resources.PolicyBinding + ) -> policy_binding_resources.PolicyBinding: + """Post-rpc interceptor for get_policy_binding + + DEPRECATED. Please use the `post_get_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_get_policy_binding` interceptor runs + before the `post_get_policy_binding_with_metadata` interceptor. + """ + return response + + def post_get_policy_binding_with_metadata( + self, + response: policy_binding_resources.PolicyBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_binding_resources.PolicyBinding, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_get_policy_binding_with_metadata` + interceptor in new development instead of the `post_get_policy_binding` interceptor. + When both interceptors are used, this `post_get_policy_binding_with_metadata` interceptor runs after the + `post_get_policy_binding` interceptor. The (possibly modified) response returned by + `post_get_policy_binding` will be passed to + `post_get_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_list_policy_bindings( + self, + request: policy_bindings_service.ListPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.ListPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_list_policy_bindings( + self, response: policy_bindings_service.ListPolicyBindingsResponse + ) -> policy_bindings_service.ListPolicyBindingsResponse: + """Post-rpc interceptor for list_policy_bindings + + DEPRECATED. Please use the `post_list_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_list_policy_bindings` interceptor runs + before the `post_list_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_list_policy_bindings_with_metadata( + self, + response: policy_bindings_service.ListPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.ListPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_list_policy_bindings_with_metadata` + interceptor in new development instead of the `post_list_policy_bindings` interceptor. + When both interceptors are used, this `post_list_policy_bindings_with_metadata` interceptor runs after the + `post_list_policy_bindings` interceptor. The (possibly modified) response returned by + `post_list_policy_bindings` will be passed to + `post_list_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_search_target_policy_bindings( + self, + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.SearchTargetPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for search_target_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_search_target_policy_bindings( + self, response: policy_bindings_service.SearchTargetPolicyBindingsResponse + ) -> policy_bindings_service.SearchTargetPolicyBindingsResponse: + """Post-rpc interceptor for search_target_policy_bindings + + DEPRECATED. Please use the `post_search_target_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_search_target_policy_bindings` interceptor runs + before the `post_search_target_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_search_target_policy_bindings_with_metadata( + self, + response: policy_bindings_service.SearchTargetPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.SearchTargetPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for search_target_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_search_target_policy_bindings_with_metadata` + interceptor in new development instead of the `post_search_target_policy_bindings` interceptor. + When both interceptors are used, this `post_search_target_policy_bindings_with_metadata` interceptor runs after the + `post_search_target_policy_bindings` interceptor. The (possibly modified) response returned by + `post_search_target_policy_bindings` will be passed to + `post_search_target_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_update_policy_binding( + self, + request: policy_bindings_service.UpdatePolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.UpdatePolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_update_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_policy_binding + + DEPRECATED. Please use the `post_update_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_update_policy_binding` interceptor runs + before the `post_update_policy_binding_with_metadata` interceptor. + """ + return response + + def post_update_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_update_policy_binding_with_metadata` + interceptor in new development instead of the `post_update_policy_binding` interceptor. + When both interceptors are used, this `post_update_policy_binding_with_metadata` interceptor runs after the + `post_update_policy_binding` interceptor. The (possibly modified) response returned by + `post_update_policy_binding` will be passed to + `post_update_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PolicyBindingsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PolicyBindingsRestInterceptor + + +class PolicyBindingsRestTransport(_BasePolicyBindingsRestTransport): + """REST backend synchronous transport for PolicyBindings. + + An interface for managing Identity and Access Management + (IAM) policy bindings. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PolicyBindingsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[PolicyBindingsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PolicyBindingsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePolicyBinding( + _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.CreatePolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: policy_bindings_service.CreatePolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.CreatePolicyBindingRequest): + The request object. Request message for + CreatePolicyBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_create_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_transcoded_request( + http_options, request + ) + + body = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.CreatePolicyBinding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "CreatePolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._CreatePolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsClient.create_policy_binding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "CreatePolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePolicyBinding( + _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.DeletePolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.DeletePolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.DeletePolicyBindingRequest): + The request object. Request message for + DeletePolicyBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_delete_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.DeletePolicyBinding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "DeletePolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._DeletePolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsClient.delete_policy_binding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "DeletePolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPolicyBinding( + _BasePolicyBindingsRestTransport._BaseGetPolicyBinding, PolicyBindingsRestStub + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.GetPolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.GetPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_binding_resources.PolicyBinding: + r"""Call the get policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.GetPolicyBindingRequest): + The request object. Request message for GetPolicyBinding + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy_binding_resources.PolicyBinding: + IAM policy binding resource. + """ + + http_options = _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_get_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.GetPolicyBinding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "GetPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._GetPolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_binding_resources.PolicyBinding() + pb_resp = policy_binding_resources.PolicyBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = policy_binding_resources.PolicyBinding.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsClient.get_policy_binding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "GetPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPolicyBindings( + _BasePolicyBindingsRestTransport._BaseListPolicyBindings, PolicyBindingsRestStub + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.ListPolicyBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.ListPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_bindings_service.ListPolicyBindingsResponse: + r"""Call the list policy bindings method over HTTP. + + Args: + request (~.policy_bindings_service.ListPolicyBindingsRequest): + The request object. Request message for + ListPolicyBindings method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy_bindings_service.ListPolicyBindingsResponse: + Response message for + ListPolicyBindings method. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_http_options() + + request, metadata = self._interceptor.pre_list_policy_bindings( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.ListPolicyBindings", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "ListPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._ListPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_bindings_service.ListPolicyBindingsResponse() + pb_resp = policy_bindings_service.ListPolicyBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_policy_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_policy_bindings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + policy_bindings_service.ListPolicyBindingsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsClient.list_policy_bindings", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "ListPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchTargetPolicyBindings( + _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.SearchTargetPolicyBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_bindings_service.SearchTargetPolicyBindingsResponse: + r"""Call the search target policy + bindings method over HTTP. + + Args: + request (~.policy_bindings_service.SearchTargetPolicyBindingsRequest): + The request object. Request message for + SearchTargetPolicyBindings method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy_bindings_service.SearchTargetPolicyBindingsResponse: + Response message for + SearchTargetPolicyBindings method. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_http_options() + + request, metadata = self._interceptor.pre_search_target_policy_bindings( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.SearchTargetPolicyBindings", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "SearchTargetPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + PolicyBindingsRestTransport._SearchTargetPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_bindings_service.SearchTargetPolicyBindingsResponse() + pb_resp = policy_bindings_service.SearchTargetPolicyBindingsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_search_target_policy_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_search_target_policy_bindings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = policy_bindings_service.SearchTargetPolicyBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsClient.search_target_policy_bindings", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "SearchTargetPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePolicyBinding( + _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.UpdatePolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: policy_bindings_service.UpdatePolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.UpdatePolicyBindingRequest): + The request object. Request message for + UpdatePolicyBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_update_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_transcoded_request( + http_options, request + ) + + body = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.UpdatePolicyBinding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "UpdatePolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._UpdatePolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsClient.update_policy_binding", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "UpdatePolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + policy_binding_resources.PolicyBinding, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + policy_bindings_service.ListPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPolicyBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + policy_bindings_service.SearchTargetPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchTargetPolicyBindings( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BasePolicyBindingsRestTransport._BaseGetOperation, PolicyBindingsRestStub + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BasePolicyBindingsRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BasePolicyBindingsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PolicyBindingsClient.GetOperation", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PolicyBindingsAsyncClient.GetOperation", + extra={ + "serviceName": "google.iam.v3.PolicyBindings", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PolicyBindingsRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5eefe3b75a6a7beeed14a7d9bcaec5611d2c6724 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/policy_bindings/transports/rest_base.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.iam_v3.types import policy_binding_resources, policy_bindings_service + +from .base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport + + +class _BasePolicyBindingsRestTransport(PolicyBindingsTransport): + """Base REST backend transport for PolicyBindings. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "policyBindingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*}/policyBindings", + "body": "policy_binding", + }, + { + "method": "post", + "uri": "/v3/{parent=folders/*/locations/*}/policyBindings", + "body": "policy_binding", + }, + { + "method": "post", + "uri": "/v3/{parent=organizations/*/locations/*}/policyBindings", + "body": "policy_binding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.CreatePolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/policyBindings/*}", + }, + { + "method": "delete", + "uri": "/v3/{name=folders/*/locations/*/policyBindings/*}", + }, + { + "method": "delete", + "uri": "/v3/{name=organizations/*/locations/*/policyBindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.DeletePolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/policyBindings/*}", + }, + { + "method": "get", + "uri": "/v3/{name=folders/*/locations/*/policyBindings/*}", + }, + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/policyBindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.GetPolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*}/policyBindings", + }, + { + "method": "get", + "uri": "/v3/{parent=folders/*/locations/*}/policyBindings", + }, + { + "method": "get", + "uri": "/v3/{parent=organizations/*/locations/*}/policyBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.ListPolicyBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchTargetPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "target": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*}/policyBindings:searchTargetPolicyBindings", + }, + { + "method": "get", + "uri": "/v3/{parent=folders/*/locations/*}/policyBindings:searchTargetPolicyBindings", + }, + { + "method": "get", + "uri": "/v3/{parent=organizations/*/locations/*}/policyBindings:searchTargetPolicyBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.SearchTargetPolicyBindingsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{policy_binding.name=projects/*/locations/*/policyBindings/*}", + "body": "policy_binding", + }, + { + "method": "patch", + "uri": "/v3/{policy_binding.name=folders/*/locations/*/policyBindings/*}", + "body": "policy_binding", + }, + { + "method": "patch", + "uri": "/v3/{policy_binding.name=organizations/*/locations/*/policyBindings/*}", + "body": "policy_binding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.UpdatePolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePolicyBindingsRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8835ba99fe94123093e9fed0964f5e92eb77db43 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PrincipalAccessBoundaryPoliciesAsyncClient +from .client import PrincipalAccessBoundaryPoliciesClient + +__all__ = ( + "PrincipalAccessBoundaryPoliciesClient", + "PrincipalAccessBoundaryPoliciesAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8d9429710d0a9842267b088de76b251156064d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/async_client.py @@ -0,0 +1,1301 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3.services.principal_access_boundary_policies import pagers +from google.cloud.iam_v3.types import ( + operation_metadata, + policy_binding_resources, + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .client import PrincipalAccessBoundaryPoliciesClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + PrincipalAccessBoundaryPoliciesTransport, +) +from .transports.grpc_asyncio import PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PrincipalAccessBoundaryPoliciesAsyncClient: + """Manages Identity and Access Management (IAM) principal access + boundary policies. + """ + + _client: PrincipalAccessBoundaryPoliciesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PrincipalAccessBoundaryPoliciesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PrincipalAccessBoundaryPoliciesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + PrincipalAccessBoundaryPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = PrincipalAccessBoundaryPoliciesClient._DEFAULT_UNIVERSE + + policy_binding_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.policy_binding_path + ) + parse_policy_binding_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_policy_binding_path + ) + principal_access_boundary_policy_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.principal_access_boundary_policy_path + ) + parse_principal_access_boundary_policy_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_principal_access_boundary_policy_path + ) + common_billing_account_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_organization_path + ) + common_project_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_project_path + ) + parse_common_project_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_project_path + ) + common_location_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_location_path + ) + parse_common_location_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesAsyncClient: The constructed client. + """ + sa_info_func = ( + PrincipalAccessBoundaryPoliciesClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + PrincipalAccessBoundaryPoliciesAsyncClient, info, *args, **kwargs + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesAsyncClient: The constructed client. + """ + sa_file_func = ( + PrincipalAccessBoundaryPoliciesClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + PrincipalAccessBoundaryPoliciesAsyncClient, filename, *args, **kwargs + ) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PrincipalAccessBoundaryPoliciesClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> PrincipalAccessBoundaryPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PrincipalAccessBoundaryPoliciesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PrincipalAccessBoundaryPoliciesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + PrincipalAccessBoundaryPoliciesTransport, + Callable[..., PrincipalAccessBoundaryPoliciesTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the principal access boundary policies async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PrincipalAccessBoundaryPoliciesTransport,Callable[..., PrincipalAccessBoundaryPoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PrincipalAccessBoundaryPoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PrincipalAccessBoundaryPoliciesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient`.", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "credentialsType": None, + }, + ) + + async def create_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + principal_access_boundary_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a principal access boundary policy, and + returns a long running operation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_create_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3.CreatePrincipalAccessBoundaryPolicyRequest( + parent="parent_value", + principal_access_boundary_policy_id="principal_access_boundary_policy_id_value", + ) + + # Make the request + operation = client.create_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.CreatePrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + CreatePrincipalAccessBoundaryPolicyRequest + method. + parent (:class:`str`): + Required. The parent resource where this principal + access boundary policy will be created. Only + organizations are supported. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy (:class:`google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy`): + Required. The principal access + boundary policy to create. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy_id (:class:`str`): + Required. The ID to use for the principal access + boundary policy, which will become the final component + of the principal access boundary policy's resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``principal_access_boundary_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + principal_access_boundary_policy, + principal_access_boundary_policy_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = principal_access_boundary_policy + if principal_access_boundary_policy_id is not None: + request.principal_access_boundary_policy_id = ( + principal_access_boundary_policy_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + r"""Gets a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_get_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3.GetPrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_principal_access_boundary_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.GetPrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + GetPrincipalAccessBoundaryPolicy method. + name (:class:`str`): + Required. The name of the principal access boundary + policy to retrieve. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy: + An IAM principal access boundary + policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_update_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3.UpdatePrincipalAccessBoundaryPolicyRequest( + ) + + # Make the request + operation = client.update_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.UpdatePrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + UpdatePrincipalAccessBoundaryPolicy + method. + principal_access_boundary_policy (:class:`google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy`): + Required. The principal access boundary policy to + update. + + The principal access boundary policy's ``name`` field is + used to identify the policy to update. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [principal_access_boundary_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = principal_access_boundary_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "principal_access_boundary_policy.name", + request.principal_access_boundary_policy.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_delete_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3.DeletePrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.DeletePrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + DeletePrincipalAccessBoundaryPolicy + method. + name (:class:`str`): + Required. The name of the principal access boundary + policy to delete. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_principal_access_boundary_policies( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPrincipalAccessBoundaryPoliciesAsyncPager: + r"""Lists principal access boundary policies. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_list_principal_access_boundary_policies(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3.ListPrincipalAccessBoundaryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_principal_access_boundary_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesRequest, dict]]): + The request object. Request message for + ListPrincipalAccessBoundaryPolicies + method. + parent (:class:`str`): + Required. The parent resource, which owns the collection + of principal access boundary policies. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.principal_access_boundary_policies.pagers.ListPrincipalAccessBoundaryPoliciesAsyncPager: + Response message for + ListPrincipalAccessBoundaryPolicies + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + ): + request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_principal_access_boundary_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPrincipalAccessBoundaryPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_principal_access_boundary_policy_bindings( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager: + r"""Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + async def sample_search_principal_access_boundary_policy_bindings(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + name="name_value", + ) + + # Make the request + page_result = client.search_principal_access_boundary_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest, dict]]): + The request object. Request message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + name (:class:`str`): + Required. The name of the principal access boundary + policy. Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.principal_access_boundary_policies.pagers.SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager: + Response message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + ): + request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_principal_access_boundary_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PrincipalAccessBoundaryPoliciesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PrincipalAccessBoundaryPoliciesAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/client.py new file mode 100644 index 0000000000000000000000000000000000000000..4118759bc72623d9bad8f2d4d981d29c3fd3d25d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/client.py @@ -0,0 +1,1760 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3.services.principal_access_boundary_policies import pagers +from google.cloud.iam_v3.types import ( + operation_metadata, + policy_binding_resources, + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + PrincipalAccessBoundaryPoliciesTransport, +) +from .transports.grpc import PrincipalAccessBoundaryPoliciesGrpcTransport +from .transports.grpc_asyncio import PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport +from .transports.rest import PrincipalAccessBoundaryPoliciesRestTransport + + +class PrincipalAccessBoundaryPoliciesClientMeta(type): + """Metaclass for the PrincipalAccessBoundaryPolicies client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PrincipalAccessBoundaryPoliciesTransport]] + _transport_registry["grpc"] = PrincipalAccessBoundaryPoliciesGrpcTransport + _transport_registry["grpc_asyncio"] = ( + PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport + ) + _transport_registry["rest"] = PrincipalAccessBoundaryPoliciesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PrincipalAccessBoundaryPoliciesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PrincipalAccessBoundaryPoliciesClient( + metaclass=PrincipalAccessBoundaryPoliciesClientMeta +): + """Manages Identity and Access Management (IAM) principal access + boundary policies. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PrincipalAccessBoundaryPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PrincipalAccessBoundaryPoliciesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def policy_binding_path( + organization: str, + location: str, + policy_binding: str, + ) -> str: + """Returns a fully-qualified policy_binding string.""" + return "organizations/{organization}/locations/{location}/policyBindings/{policy_binding}".format( + organization=organization, + location=location, + policy_binding=policy_binding, + ) + + @staticmethod + def parse_policy_binding_path(path: str) -> Dict[str, str]: + """Parses a policy_binding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/policyBindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def principal_access_boundary_policy_path( + organization: str, + location: str, + principal_access_boundary_policy: str, + ) -> str: + """Returns a fully-qualified principal_access_boundary_policy string.""" + return "organizations/{organization}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy}".format( + organization=organization, + location=location, + principal_access_boundary_policy=principal_access_boundary_policy, + ) + + @staticmethod + def parse_principal_access_boundary_policy_path(path: str) -> Dict[str, str]: + """Parses a principal_access_boundary_policy path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/principalAccessBoundaryPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ( + PrincipalAccessBoundaryPoliciesClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ( + PrincipalAccessBoundaryPoliciesClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PrincipalAccessBoundaryPoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PrincipalAccessBoundaryPoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + PrincipalAccessBoundaryPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PrincipalAccessBoundaryPoliciesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + PrincipalAccessBoundaryPoliciesTransport, + Callable[..., PrincipalAccessBoundaryPoliciesTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the principal access boundary policies client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PrincipalAccessBoundaryPoliciesTransport,Callable[..., PrincipalAccessBoundaryPoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PrincipalAccessBoundaryPoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PrincipalAccessBoundaryPoliciesClient._read_environment_variables() + ) + self._client_cert_source = ( + PrincipalAccessBoundaryPoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + PrincipalAccessBoundaryPoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, PrincipalAccessBoundaryPoliciesTransport + ) + if transport_provided: + # transport is a PrincipalAccessBoundaryPoliciesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PrincipalAccessBoundaryPoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or PrincipalAccessBoundaryPoliciesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PrincipalAccessBoundaryPoliciesTransport], + Callable[..., PrincipalAccessBoundaryPoliciesTransport], + ] = ( + PrincipalAccessBoundaryPoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., PrincipalAccessBoundaryPoliciesTransport], transport + ) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3.PrincipalAccessBoundaryPoliciesClient`.", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "credentialsType": None, + }, + ) + + def create_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + principal_access_boundary_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a principal access boundary policy, and + returns a long running operation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_create_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3.CreatePrincipalAccessBoundaryPolicyRequest( + parent="parent_value", + principal_access_boundary_policy_id="principal_access_boundary_policy_id_value", + ) + + # Make the request + operation = client.create_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.CreatePrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + CreatePrincipalAccessBoundaryPolicyRequest + method. + parent (str): + Required. The parent resource where this principal + access boundary policy will be created. Only + organizations are supported. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy (google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy): + Required. The principal access + boundary policy to create. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy_id (str): + Required. The ID to use for the principal access + boundary policy, which will become the final component + of the principal access boundary policy's resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``principal_access_boundary_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + principal_access_boundary_policy, + principal_access_boundary_policy_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = ( + principal_access_boundary_policy + ) + if principal_access_boundary_policy_id is not None: + request.principal_access_boundary_policy_id = ( + principal_access_boundary_policy_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + r"""Gets a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_get_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3.GetPrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_principal_access_boundary_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.GetPrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + GetPrincipalAccessBoundaryPolicy method. + name (str): + Required. The name of the principal access boundary + policy to retrieve. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy: + An IAM principal access boundary + policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_update_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3.UpdatePrincipalAccessBoundaryPolicyRequest( + ) + + # Make the request + operation = client.update_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.UpdatePrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + UpdatePrincipalAccessBoundaryPolicy + method. + principal_access_boundary_policy (google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy): + Required. The principal access boundary policy to + update. + + The principal access boundary policy's ``name`` field is + used to identify the policy to update. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [principal_access_boundary_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = ( + principal_access_boundary_policy + ) + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "principal_access_boundary_policy.name", + request.principal_access_boundary_policy.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_delete_principal_access_boundary_policy(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3.DeletePrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.DeletePrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + DeletePrincipalAccessBoundaryPolicy + method. + name (str): + Required. The name of the principal access boundary + policy to delete. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_principal_access_boundary_policies( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPrincipalAccessBoundaryPoliciesPager: + r"""Lists principal access boundary policies. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_list_principal_access_boundary_policies(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3.ListPrincipalAccessBoundaryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_principal_access_boundary_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesRequest, dict]): + The request object. Request message for + ListPrincipalAccessBoundaryPolicies + method. + parent (str): + Required. The parent resource, which owns the collection + of principal access boundary policies. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.principal_access_boundary_policies.pagers.ListPrincipalAccessBoundaryPoliciesPager: + Response message for + ListPrincipalAccessBoundaryPolicies + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + ): + request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_principal_access_boundary_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPrincipalAccessBoundaryPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_principal_access_boundary_policy_bindings( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchPrincipalAccessBoundaryPolicyBindingsPager: + r"""Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3 + + def sample_search_principal_access_boundary_policy_bindings(): + # Create a client + client = iam_v3.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + name="name_value", + ) + + # Make the request + page_result = client.search_principal_access_boundary_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest, dict]): + The request object. Request message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + name (str): + Required. The name of the principal access boundary + policy. Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3.services.principal_access_boundary_policies.pagers.SearchPrincipalAccessBoundaryPolicyBindingsPager: + Response message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + ): + request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.search_principal_access_boundary_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPrincipalAccessBoundaryPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PrincipalAccessBoundaryPoliciesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PrincipalAccessBoundaryPoliciesClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6cf8b1ba5759d8ab8025fc5319649fd2daf24 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/pagers.py @@ -0,0 +1,405 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_v3.types import ( + policy_binding_resources, + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + + +class ListPrincipalAccessBoundaryPoliciesPager: + """A pager for iterating through ``list_principal_access_boundary_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``principal_access_boundary_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPrincipalAccessBoundaryPolicies`` requests and continue to iterate + through the ``principal_access_boundary_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ], + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesRequest): + The initial request object. + response (google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__( + self, + ) -> Iterator[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ]: + for page in self.pages: + yield from page.principal_access_boundary_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPrincipalAccessBoundaryPoliciesAsyncPager: + """A pager for iterating through ``list_principal_access_boundary_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``principal_access_boundary_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPrincipalAccessBoundaryPolicies`` requests and continue to iterate + through the ``principal_access_boundary_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ], + ], + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesRequest): + The initial request object. + response (google.cloud.iam_v3.types.ListPrincipalAccessBoundaryPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ]: + async def async_generator(): + async for page in self.pages: + for response in page.principal_access_boundary_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchPrincipalAccessBoundaryPolicyBindingsPager: + """A pager for iterating through ``search_principal_access_boundary_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchPrincipalAccessBoundaryPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ], + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy_binding_resources.PolicyBinding]: + for page in self.pages: + yield from page.policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager: + """A pager for iterating through ``search_principal_access_boundary_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchPrincipalAccessBoundaryPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ], + ], + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy_binding_resources.PolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..572b487008f51f9fa2f5ceaf3928c1e83129cd1e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PrincipalAccessBoundaryPoliciesTransport +from .grpc import PrincipalAccessBoundaryPoliciesGrpcTransport +from .grpc_asyncio import PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport +from .rest import ( + PrincipalAccessBoundaryPoliciesRestInterceptor, + PrincipalAccessBoundaryPoliciesRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PrincipalAccessBoundaryPoliciesTransport]] +_transport_registry["grpc"] = PrincipalAccessBoundaryPoliciesGrpcTransport +_transport_registry["grpc_asyncio"] = ( + PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport +) +_transport_registry["rest"] = PrincipalAccessBoundaryPoliciesRestTransport + +__all__ = ( + "PrincipalAccessBoundaryPoliciesTransport", + "PrincipalAccessBoundaryPoliciesGrpcTransport", + "PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport", + "PrincipalAccessBoundaryPoliciesRestTransport", + "PrincipalAccessBoundaryPoliciesRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..63a7c3b91d3f038744ca506f4643ded7cb04cfee --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/base.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3 import gapic_version as package_version +from google.cloud.iam_v3.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PrincipalAccessBoundaryPoliciesTransport(abc.ABC): + """Abstract transport class for PrincipalAccessBoundaryPolicies.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.create_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.get_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.get_principal_access_boundary_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.update_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.delete_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.list_principal_access_boundary_policies: gapic_v1.method.wrap_method( + self.list_principal_access_boundary_policies, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_principal_access_boundary_policy_bindings: gapic_v1.method.wrap_method( + self.search_principal_access_boundary_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + Union[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + Awaitable[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ], + ], + ]: + raise NotImplementedError() + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + Union[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + Awaitable[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + Union[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + Awaitable[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PrincipalAccessBoundaryPoliciesTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5e1ba4baa74aea2746cd26351545c0500e548e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/grpc.py @@ -0,0 +1,585 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_v3.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO, PrincipalAccessBoundaryPoliciesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PrincipalAccessBoundaryPoliciesGrpcTransport( + PrincipalAccessBoundaryPoliciesTransport +): + """gRPC backend transport for PrincipalAccessBoundaryPolicies. + + Manages Identity and Access Management (IAM) principal access + boundary policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the create principal access + boundary policy method over gRPC. + + Creates a principal access boundary policy, and + returns a long running operation. + + Returns: + Callable[[~.CreatePrincipalAccessBoundaryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_principal_access_boundary_policy" not in self._stubs: + self._stubs["create_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/CreatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_principal_access_boundary_policy"] + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ]: + r"""Return a callable for the get principal access boundary + policy method over gRPC. + + Gets a principal access boundary policy. + + Returns: + Callable[[~.GetPrincipalAccessBoundaryPolicyRequest], + ~.PrincipalAccessBoundaryPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_principal_access_boundary_policy" not in self._stubs: + self._stubs["get_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/GetPrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.deserialize, + ) + ) + return self._stubs["get_principal_access_boundary_policy"] + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the update principal access + boundary policy method over gRPC. + + Updates a principal access boundary policy. + + Returns: + Callable[[~.UpdatePrincipalAccessBoundaryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_principal_access_boundary_policy" not in self._stubs: + self._stubs["update_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/UpdatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_principal_access_boundary_policy"] + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete principal access + boundary policy method over gRPC. + + Deletes a principal access boundary policy. + + Returns: + Callable[[~.DeletePrincipalAccessBoundaryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_principal_access_boundary_policy" not in self._stubs: + self._stubs["delete_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/DeletePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_principal_access_boundary_policy"] + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ]: + r"""Return a callable for the list principal access boundary + policies method over gRPC. + + Lists principal access boundary policies. + + Returns: + Callable[[~.ListPrincipalAccessBoundaryPoliciesRequest], + ~.ListPrincipalAccessBoundaryPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_principal_access_boundary_policies" not in self._stubs: + self._stubs["list_principal_access_boundary_policies"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/ListPrincipalAccessBoundaryPolicies", + request_serializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_principal_access_boundary_policies"] + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ]: + r"""Return a callable for the search principal access + boundary policy bindings method over gRPC. + + Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + Returns: + Callable[[~.SearchPrincipalAccessBoundaryPolicyBindingsRequest], + ~.SearchPrincipalAccessBoundaryPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_principal_access_boundary_policy_bindings" not in self._stubs: + self._stubs["search_principal_access_boundary_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/SearchPrincipalAccessBoundaryPolicyBindings", + request_serializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_principal_access_boundary_policy_bindings"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PrincipalAccessBoundaryPoliciesGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..2968ad1613fcea3febde00f525f9335cfcac97e0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/grpc_asyncio.py @@ -0,0 +1,671 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_v3.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO, PrincipalAccessBoundaryPoliciesTransport +from .grpc import PrincipalAccessBoundaryPoliciesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport( + PrincipalAccessBoundaryPoliciesTransport +): + """gRPC AsyncIO backend transport for PrincipalAccessBoundaryPolicies. + + Manages Identity and Access Management (IAM) principal access + boundary policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create principal access + boundary policy method over gRPC. + + Creates a principal access boundary policy, and + returns a long running operation. + + Returns: + Callable[[~.CreatePrincipalAccessBoundaryPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_principal_access_boundary_policy" not in self._stubs: + self._stubs["create_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/CreatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_principal_access_boundary_policy"] + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + Awaitable[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ], + ]: + r"""Return a callable for the get principal access boundary + policy method over gRPC. + + Gets a principal access boundary policy. + + Returns: + Callable[[~.GetPrincipalAccessBoundaryPolicyRequest], + Awaitable[~.PrincipalAccessBoundaryPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_principal_access_boundary_policy" not in self._stubs: + self._stubs["get_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/GetPrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.deserialize, + ) + ) + return self._stubs["get_principal_access_boundary_policy"] + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update principal access + boundary policy method over gRPC. + + Updates a principal access boundary policy. + + Returns: + Callable[[~.UpdatePrincipalAccessBoundaryPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_principal_access_boundary_policy" not in self._stubs: + self._stubs["update_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/UpdatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_principal_access_boundary_policy"] + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete principal access + boundary policy method over gRPC. + + Deletes a principal access boundary policy. + + Returns: + Callable[[~.DeletePrincipalAccessBoundaryPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_principal_access_boundary_policy" not in self._stubs: + self._stubs["delete_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/DeletePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_principal_access_boundary_policy"] + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + Awaitable[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ], + ]: + r"""Return a callable for the list principal access boundary + policies method over gRPC. + + Lists principal access boundary policies. + + Returns: + Callable[[~.ListPrincipalAccessBoundaryPoliciesRequest], + Awaitable[~.ListPrincipalAccessBoundaryPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_principal_access_boundary_policies" not in self._stubs: + self._stubs["list_principal_access_boundary_policies"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/ListPrincipalAccessBoundaryPolicies", + request_serializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_principal_access_boundary_policies"] + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + Awaitable[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ], + ]: + r"""Return a callable for the search principal access + boundary policy bindings method over gRPC. + + Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + Returns: + Callable[[~.SearchPrincipalAccessBoundaryPolicyBindingsRequest], + Awaitable[~.SearchPrincipalAccessBoundaryPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_principal_access_boundary_policy_bindings" not in self._stubs: + self._stubs["search_principal_access_boundary_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3.PrincipalAccessBoundaryPolicies/SearchPrincipalAccessBoundaryPolicyBindings", + request_serializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_principal_access_boundary_policy_bindings"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_principal_access_boundary_policy: self._wrap_method( + self.create_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.get_principal_access_boundary_policy: self._wrap_method( + self.get_principal_access_boundary_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_principal_access_boundary_policy: self._wrap_method( + self.update_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_principal_access_boundary_policy: self._wrap_method( + self.delete_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.list_principal_access_boundary_policies: self._wrap_method( + self.list_principal_access_boundary_policies, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_principal_access_boundary_policy_bindings: self._wrap_method( + self.search_principal_access_boundary_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..2efc800132059e95339d3f814634ae63f72188a5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/rest.py @@ -0,0 +1,1806 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.iam_v3.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePrincipalAccessBoundaryPoliciesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PrincipalAccessBoundaryPoliciesRestInterceptor: + """Interceptor for PrincipalAccessBoundaryPolicies. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PrincipalAccessBoundaryPoliciesRestTransport. + + .. code-block:: python + class MyCustomPrincipalAccessBoundaryPoliciesInterceptor(PrincipalAccessBoundaryPoliciesRestInterceptor): + def pre_create_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_principal_access_boundary_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_principal_access_boundary_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_principal_access_boundary_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_principal_access_boundary_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PrincipalAccessBoundaryPoliciesRestTransport(interceptor=MyCustomPrincipalAccessBoundaryPoliciesInterceptor()) + client = PrincipalAccessBoundaryPoliciesClient(transport=transport) + + + """ + + def pre_create_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_create_principal_access_boundary_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_principal_access_boundary_policy + + DEPRECATED. Please use the `post_create_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_create_principal_access_boundary_policy` interceptor runs + before the `post_create_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_create_principal_access_boundary_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_create_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_create_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_create_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_create_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_create_principal_access_boundary_policy` will be passed to + `post_create_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_delete_principal_access_boundary_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_principal_access_boundary_policy + + DEPRECATED. Please use the `post_delete_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_delete_principal_access_boundary_policy` interceptor runs + before the `post_delete_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_delete_principal_access_boundary_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_delete_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_delete_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_delete_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_delete_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_delete_principal_access_boundary_policy` will be passed to + `post_delete_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_get_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_get_principal_access_boundary_policy( + self, + response: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + """Post-rpc interceptor for get_principal_access_boundary_policy + + DEPRECATED. Please use the `post_get_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_get_principal_access_boundary_policy` interceptor runs + before the `post_get_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_get_principal_access_boundary_policy_with_metadata( + self, + response: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_get_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_get_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_get_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_get_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_get_principal_access_boundary_policy` will be passed to + `post_get_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_list_principal_access_boundary_policies( + self, + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_principal_access_boundary_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_list_principal_access_boundary_policies( + self, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ) -> principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse: + """Post-rpc interceptor for list_principal_access_boundary_policies + + DEPRECATED. Please use the `post_list_principal_access_boundary_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_list_principal_access_boundary_policies` interceptor runs + before the `post_list_principal_access_boundary_policies_with_metadata` interceptor. + """ + return response + + def post_list_principal_access_boundary_policies_with_metadata( + self, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_principal_access_boundary_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_list_principal_access_boundary_policies_with_metadata` + interceptor in new development instead of the `post_list_principal_access_boundary_policies` interceptor. + When both interceptors are used, this `post_list_principal_access_boundary_policies_with_metadata` interceptor runs after the + `post_list_principal_access_boundary_policies` interceptor. The (possibly modified) response returned by + `post_list_principal_access_boundary_policies` will be passed to + `post_list_principal_access_boundary_policies_with_metadata`. + """ + return response, metadata + + def pre_search_principal_access_boundary_policy_bindings( + self, + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for search_principal_access_boundary_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_search_principal_access_boundary_policy_bindings( + self, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ) -> principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse: + """Post-rpc interceptor for search_principal_access_boundary_policy_bindings + + DEPRECATED. Please use the `post_search_principal_access_boundary_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_search_principal_access_boundary_policy_bindings` interceptor runs + before the `post_search_principal_access_boundary_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_search_principal_access_boundary_policy_bindings_with_metadata( + self, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for search_principal_access_boundary_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_search_principal_access_boundary_policy_bindings_with_metadata` + interceptor in new development instead of the `post_search_principal_access_boundary_policy_bindings` interceptor. + When both interceptors are used, this `post_search_principal_access_boundary_policy_bindings_with_metadata` interceptor runs after the + `post_search_principal_access_boundary_policy_bindings` interceptor. The (possibly modified) response returned by + `post_search_principal_access_boundary_policy_bindings` will be passed to + `post_search_principal_access_boundary_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_update_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_update_principal_access_boundary_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_principal_access_boundary_policy + + DEPRECATED. Please use the `post_update_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_update_principal_access_boundary_policy` interceptor runs + before the `post_update_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_update_principal_access_boundary_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_update_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_update_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_update_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_update_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_update_principal_access_boundary_policy` will be passed to + `post_update_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PrincipalAccessBoundaryPoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PrincipalAccessBoundaryPoliciesRestInterceptor + + +class PrincipalAccessBoundaryPoliciesRestTransport( + _BasePrincipalAccessBoundaryPoliciesRestTransport +): + """REST backend synchronous transport for PrincipalAccessBoundaryPolicies. + + Manages Identity and Access Management (IAM) principal access + boundary policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PrincipalAccessBoundaryPoliciesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[PrincipalAccessBoundaryPoliciesRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or PrincipalAccessBoundaryPoliciesRestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.CreatePrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + CreatePrincipalAccessBoundaryPolicyRequest + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_create_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + body = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.CreatePrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "CreatePrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._CreatePrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.create_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "CreatePrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.DeletePrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + DeletePrincipalAccessBoundaryPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_delete_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.DeletePrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "DeletePrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._DeletePrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.delete_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "DeletePrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.GetPrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + r"""Call the get principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + GetPrincipalAccessBoundaryPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + An IAM principal access boundary + policy resource. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.GetPrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "GetPrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._GetPrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy() + pb_resp = principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.get_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "GetPrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPrincipalAccessBoundaryPolicies( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.ListPrincipalAccessBoundaryPolicies" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse: + r"""Call the list principal access + boundary policies method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest): + The request object. Request message for + ListPrincipalAccessBoundaryPolicies + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse: + Response message for + ListPrincipalAccessBoundaryPolicies + method. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_http_options() + + request, metadata = ( + self._interceptor.pre_list_principal_access_boundary_policies( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.ListPrincipalAccessBoundaryPolicies", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "ListPrincipalAccessBoundaryPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._ListPrincipalAccessBoundaryPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse() + pb_resp = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_principal_access_boundary_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_principal_access_boundary_policies_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.list_principal_access_boundary_policies", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "ListPrincipalAccessBoundaryPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchPrincipalAccessBoundaryPolicyBindings( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.SearchPrincipalAccessBoundaryPolicyBindings" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse: + r"""Call the search principal access + boundary policy bindings method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest): + The request object. Request message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse: + Response message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_http_options() + + request, metadata = ( + self._interceptor.pre_search_principal_access_boundary_policy_bindings( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.SearchPrincipalAccessBoundaryPolicyBindings", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "SearchPrincipalAccessBoundaryPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._SearchPrincipalAccessBoundaryPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse() + pb_resp = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_search_principal_access_boundary_policy_bindings( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_search_principal_access_boundary_policy_bindings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.search_principal_access_boundary_policy_bindings", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "SearchPrincipalAccessBoundaryPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.UpdatePrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + UpdatePrincipalAccessBoundaryPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_update_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + body = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.UpdatePrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "UpdatePrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._UpdatePrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.update_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "UpdatePrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPrincipalAccessBoundaryPolicies( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchPrincipalAccessBoundaryPolicyBindings( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash("PrincipalAccessBoundaryPoliciesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3.PrincipalAccessBoundaryPoliciesClient.GetOperation", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3.PrincipalAccessBoundaryPoliciesAsyncClient.GetOperation", + extra={ + "serviceName": "google.iam.v3.PrincipalAccessBoundaryPolicies", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PrincipalAccessBoundaryPoliciesRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb17a28a926301f4f432ed131cec2477a5ebf67 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/services/principal_access_boundary_policies/transports/rest_base.py @@ -0,0 +1,447 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.iam_v3.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO, PrincipalAccessBoundaryPoliciesTransport + + +class _BasePrincipalAccessBoundaryPoliciesRestTransport( + PrincipalAccessBoundaryPoliciesTransport +): + """Base REST backend transport for PrincipalAccessBoundaryPolicies. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "principalAccessBoundaryPolicyId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=organizations/*/locations/*}/principalAccessBoundaryPolicies", + "body": "principal_access_boundary_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPrincipalAccessBoundaryPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=organizations/*/locations/*}/principalAccessBoundaryPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchPrincipalAccessBoundaryPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}:searchPolicyBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{principal_access_boundary_policy.name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", + "body": "principal_access_boundary_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=organizations/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePrincipalAccessBoundaryPoliciesRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0caa3a5e8dd71799f29ece5293ff01b722d4fa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/__init__.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .operation_metadata import ( + OperationMetadata, +) +from .policy_binding_resources import ( + PolicyBinding, +) +from .policy_bindings_service import ( + CreatePolicyBindingRequest, + DeletePolicyBindingRequest, + GetPolicyBindingRequest, + ListPolicyBindingsRequest, + ListPolicyBindingsResponse, + SearchTargetPolicyBindingsRequest, + SearchTargetPolicyBindingsResponse, + UpdatePolicyBindingRequest, +) +from .principal_access_boundary_policies_service import ( + CreatePrincipalAccessBoundaryPolicyRequest, + DeletePrincipalAccessBoundaryPolicyRequest, + GetPrincipalAccessBoundaryPolicyRequest, + ListPrincipalAccessBoundaryPoliciesRequest, + ListPrincipalAccessBoundaryPoliciesResponse, + SearchPrincipalAccessBoundaryPolicyBindingsRequest, + SearchPrincipalAccessBoundaryPolicyBindingsResponse, + UpdatePrincipalAccessBoundaryPolicyRequest, +) +from .principal_access_boundary_policy_resources import ( + PrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPolicyDetails, + PrincipalAccessBoundaryPolicyRule, +) + +__all__ = ( + "OperationMetadata", + "PolicyBinding", + "CreatePolicyBindingRequest", + "DeletePolicyBindingRequest", + "GetPolicyBindingRequest", + "ListPolicyBindingsRequest", + "ListPolicyBindingsResponse", + "SearchTargetPolicyBindingsRequest", + "SearchTargetPolicyBindingsResponse", + "UpdatePolicyBindingRequest", + "CreatePrincipalAccessBoundaryPolicyRequest", + "DeletePrincipalAccessBoundaryPolicyRequest", + "GetPrincipalAccessBoundaryPolicyRequest", + "ListPrincipalAccessBoundaryPoliciesRequest", + "ListPrincipalAccessBoundaryPoliciesResponse", + "SearchPrincipalAccessBoundaryPolicyBindingsRequest", + "SearchPrincipalAccessBoundaryPolicyBindingsResponse", + "UpdatePrincipalAccessBoundaryPolicyRequest", + "PrincipalAccessBoundaryPolicy", + "PrincipalAccessBoundaryPolicyDetails", + "PrincipalAccessBoundaryPolicyRule", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/operation_metadata.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/operation_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..85bb60cfa9eb9373ea78014e5f11a88e90c25e4f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/operation_metadata.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v3", + manifest={ + "OperationMetadata", + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/policy_binding_resources.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/policy_binding_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..fe70ee5e4dc7cd99aa6d3708c5a0ad85230e4ca7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/policy_binding_resources.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v3", + manifest={ + "PolicyBinding", + }, +) + + +class PolicyBinding(proto.Message): + r"""IAM policy binding resource. + + Attributes: + name (str): + Identifier. The name of the policy binding, in the format + ``{binding_parent/locations/{location}/policyBindings/{policy_binding_id}``. + The binding parent is the closest Resource Manager resource + (project, folder, or organization) to the binding target. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + uid (str): + Output only. The globally unique ID of the + policy binding. Assigned when the policy binding + is created. + etag (str): + Optional. The etag for the policy binding. + If this is provided on update, it must match the + server's etag. + display_name (str): + Optional. The description of the policy + binding. Must be less than or equal to 63 + characters. + annotations (MutableMapping[str, str]): + Optional. User-defined annotations. See + https://google.aip.dev/148#annotations for more + details such as format and size limitations + target (google.cloud.iam_v3.types.PolicyBinding.Target): + Required. Immutable. Target is the full + resource name of the resource to which the + policy will be bound. Immutable once set. + policy_kind (google.cloud.iam_v3.types.PolicyBinding.PolicyKind): + Immutable. The kind of the policy to attach + in this binding. This field must be one of the + following: + + - Left empty (will be automatically set to the + policy kind) + - The input policy kind + policy (str): + Required. Immutable. The resource name of the + policy to be bound. The binding parent and + policy must belong to the same organization. + policy_uid (str): + Output only. The globally unique ID of the + policy to be bound. + condition (google.type.expr_pb2.Expr): + Optional. The condition to apply to the policy binding. When + set, the ``expression`` field in the ``Expr`` must include + from 1 to 10 subexpressions, joined by the "\|\|"(Logical + OR), "&&"(Logical AND) or "!"(Logical NOT) operators and + cannot contain more than 250 characters. + + The condition is currently only supported when bound to + policies of kind principal access boundary. + + When the bound policy is a principal access boundary policy, + the only supported attributes in any subexpression are + ``principal.type`` and ``principal.subject``. An example + expression is: "principal.type == + 'iam.googleapis.com/ServiceAccount'" or "principal.subject + == 'bob@example.com'". + + Allowed operations for ``principal.subject``: + + - ``principal.subject == `` + - ``principal.subject != `` + - ``principal.subject in []`` + - ``principal.subject.startsWith()`` + - ``principal.subject.endsWith()`` + + Allowed operations for ``principal.type``: + + - ``principal.type == `` + - ``principal.type != `` + - ``principal.type in []`` + + Supported principal types are Workspace, Workforce Pool, + Workload Pool and Service Account. Allowed string must be + one of: + + - iam.googleapis.com/WorkspaceIdentity + - iam.googleapis.com/WorkforcePoolIdentity + - iam.googleapis.com/WorkloadPoolIdentity + - iam.googleapis.com/ServiceAccount + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the policy binding + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the policy binding + was most recently updated. + """ + + class PolicyKind(proto.Enum): + r"""Different policy kinds supported in this binding. + + Values: + POLICY_KIND_UNSPECIFIED (0): + Unspecified policy kind; Not a valid state + PRINCIPAL_ACCESS_BOUNDARY (1): + Principal access boundary policy kind + """ + + POLICY_KIND_UNSPECIFIED = 0 + PRINCIPAL_ACCESS_BOUNDARY = 1 + + class Target(proto.Message): + r"""Target is the full resource name of the resource to which the + policy will be bound. Immutable once set. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + principal_set (str): + Immutable. Full Resource Name used for principal access + boundary policy bindings. The principal set must be directly + parented by the policy binding's parent or same as the + parent if the target is a project/folder/organization. + + Examples: + + - For binding's parented by an organization: + + - Organization: + ``//cloudresourcemanager.googleapis.com/organizations/ORGANIZATION_ID`` + - Workforce Identity: + ``//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID`` + - Workspace Identity: + ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + + - For binding's parented by a folder: + + - Folder: + ``//cloudresourcemanager.googleapis.com/folders/FOLDER_ID`` + + - For binding's parented by a project: + + - Project: + + - ``//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER`` + - ``//cloudresourcemanager.googleapis.com/projects/PROJECT_ID`` + + - Workload Identity Pool: + ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/LOCATION/workloadIdentityPools/WORKLOAD_POOL_ID`` + + This field is a member of `oneof`_ ``target``. + """ + + principal_set: str = proto.Field( + proto.STRING, + number=1, + oneof="target", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + target: Target = proto.Field( + proto.MESSAGE, + number=6, + message=Target, + ) + policy_kind: PolicyKind = proto.Field( + proto.ENUM, + number=11, + enum=PolicyKind, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_uid: str = proto.Field( + proto.STRING, + number=12, + ) + condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=8, + message=expr_pb2.Expr, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/policy_bindings_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/policy_bindings_service.py new file mode 100644 index 0000000000000000000000000000000000000000..951f6421e8507246f14a06506c55702b27a8b1ca --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/policy_bindings_service.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.iam_v3.types import policy_binding_resources + +__protobuf__ = proto.module( + package="google.iam.v3", + manifest={ + "CreatePolicyBindingRequest", + "GetPolicyBindingRequest", + "UpdatePolicyBindingRequest", + "DeletePolicyBindingRequest", + "ListPolicyBindingsRequest", + "ListPolicyBindingsResponse", + "SearchTargetPolicyBindingsRequest", + "SearchTargetPolicyBindingsResponse", + }, +) + + +class CreatePolicyBindingRequest(proto.Message): + r"""Request message for CreatePolicyBinding method. + + Attributes: + parent (str): + Required. The parent resource where this policy binding will + be created. The binding parent is the closest Resource + Manager resource (project, folder or organization) to the + binding target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + policy_binding_id (str): + Required. The ID to use for the policy binding, which will + become the final component of the policy binding's resource + name. + + This value must start with a lowercase letter followed by up + to 62 lowercase letters, numbers, hyphens, or dots. Pattern, + /[a-z][a-z0-9-.]{2,62}/. + policy_binding (google.cloud.iam_v3.types.PolicyBinding): + Required. The policy binding to create. + validate_only (bool): + Optional. If set, validate the request and + preview the creation, but do not actually post + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + policy_binding_id: str = proto.Field( + proto.STRING, + number=2, + ) + policy_binding: policy_binding_resources.PolicyBinding = proto.Field( + proto.MESSAGE, + number=3, + message=policy_binding_resources.PolicyBinding, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetPolicyBindingRequest(proto.Message): + r"""Request message for GetPolicyBinding method. + + Attributes: + name (str): + Required. The name of the policy binding to retrieve. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePolicyBindingRequest(proto.Message): + r"""Request message for UpdatePolicyBinding method. + + Attributes: + policy_binding (google.cloud.iam_v3.types.PolicyBinding): + Required. The policy binding to update. + + The policy binding's ``name`` field is used to identify the + policy binding to update. + validate_only (bool): + Optional. If set, validate the request and + preview the update, but do not actually post it. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update + """ + + policy_binding: policy_binding_resources.PolicyBinding = proto.Field( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePolicyBindingRequest(proto.Message): + r"""Request message for DeletePolicyBinding method. + + Attributes: + name (str): + Required. The name of the policy binding to delete. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + etag (str): + Optional. The etag of the policy binding. + If this is provided, it must match the server's + etag. + validate_only (bool): + Optional. If set, validate the request and + preview the deletion, but do not actually post + it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListPolicyBindingsRequest(proto.Message): + r"""Request message for ListPolicyBindings method. + + Attributes: + parent (str): + Required. The parent resource, which owns the collection of + policy bindings. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + page_size (int): + Optional. The maximum number of policy + bindings to return. The service may return fewer + than this value. + + If unspecified, at most 50 policy bindings will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListPolicyBindings`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListPolicyBindings`` must match the call that provided the + page token. + filter (str): + Optional. An expression for filtering the results of the + request. Filter rules are case insensitive. Some eligible + fields for filtering are: + + - ``target`` + - ``policy`` + + Some examples of filter queries: + + - ``target:ex*``: The binding target's name starts with + "ex". + - ``target:example``: The binding target's name is + ``example``. + - ``policy:example``: The binding policy's name is + ``example``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPolicyBindingsResponse(proto.Message): + r"""Response message for ListPolicyBindings method. + + Attributes: + policy_bindings (MutableSequence[google.cloud.iam_v3.types.PolicyBinding]): + The policy bindings from the specified + parent. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + policy_bindings: MutableSequence[policy_binding_resources.PolicyBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchTargetPolicyBindingsRequest(proto.Message): + r"""Request message for SearchTargetPolicyBindings method. + + Attributes: + target (str): + Required. The target resource, which is bound to the policy + in the binding. + + Format: + + - ``//iam.googleapis.com/locations/global/workforcePools/POOL_ID`` + - ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID`` + - ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + - ``//cloudresourcemanager.googleapis.com/projects/{project_number}`` + - ``//cloudresourcemanager.googleapis.com/folders/{folder_id}`` + - ``//cloudresourcemanager.googleapis.com/organizations/{organization_id}`` + page_size (int): + Optional. The maximum number of policy + bindings to return. The service may return fewer + than this value. + + If unspecified, at most 50 policy bindings will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``SearchTargetPolicyBindingsRequest`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``SearchTargetPolicyBindingsRequest`` must match the call + that provided the page token. + parent (str): + Required. The parent resource where this search will be + performed. This should be the nearest Resource Manager + resource (project, folder, or organization) to the target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + """ + + target: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=5, + ) + + +class SearchTargetPolicyBindingsResponse(proto.Message): + r"""Response message for SearchTargetPolicyBindings method. + + Attributes: + policy_bindings (MutableSequence[google.cloud.iam_v3.types.PolicyBinding]): + The policy bindings bound to the specified + target. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + policy_bindings: MutableSequence[policy_binding_resources.PolicyBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/principal_access_boundary_policies_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/principal_access_boundary_policies_service.py new file mode 100644 index 0000000000000000000000000000000000000000..ac0552725826da78238af2c2a2ce15fc862e690c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/principal_access_boundary_policies_service.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.iam_v3.types import ( + policy_binding_resources, + principal_access_boundary_policy_resources, +) + +__protobuf__ = proto.module( + package="google.iam.v3", + manifest={ + "CreatePrincipalAccessBoundaryPolicyRequest", + "GetPrincipalAccessBoundaryPolicyRequest", + "UpdatePrincipalAccessBoundaryPolicyRequest", + "DeletePrincipalAccessBoundaryPolicyRequest", + "ListPrincipalAccessBoundaryPoliciesRequest", + "ListPrincipalAccessBoundaryPoliciesResponse", + "SearchPrincipalAccessBoundaryPolicyBindingsRequest", + "SearchPrincipalAccessBoundaryPolicyBindingsResponse", + }, +) + + +class CreatePrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for + CreatePrincipalAccessBoundaryPolicyRequest method. + + Attributes: + parent (str): + Required. The parent resource where this principal access + boundary policy will be created. Only organizations are + supported. + + Format: + ``organizations/{organization_id}/locations/{location}`` + principal_access_boundary_policy_id (str): + Required. The ID to use for the principal access boundary + policy, which will become the final component of the + principal access boundary policy's resource name. + + This value must start with a lowercase letter followed by up + to 62 lowercase letters, numbers, hyphens, or dots. Pattern, + /[a-z][a-z0-9-.]{2,62}/. + principal_access_boundary_policy (google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy): + Required. The principal access boundary + policy to create. + validate_only (bool): + Optional. If set, validate the request and + preview the creation, but do not actually post + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + principal_access_boundary_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + principal_access_boundary_policy: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy = proto.Field( + proto.MESSAGE, + number=3, + message=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetPrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for GetPrincipalAccessBoundaryPolicy method. + + Attributes: + name (str): + Required. The name of the principal access boundary policy + to retrieve. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for UpdatePrincipalAccessBoundaryPolicy + method. + + Attributes: + principal_access_boundary_policy (google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy): + Required. The principal access boundary policy to update. + + The principal access boundary policy's ``name`` field is + used to identify the policy to update. + validate_only (bool): + Optional. If set, validate the request and + preview the update, but do not actually post it. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update + """ + + principal_access_boundary_policy: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy = proto.Field( + proto.MESSAGE, + number=1, + message=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for DeletePrincipalAccessBoundaryPolicy + method. + + Attributes: + name (str): + Required. The name of the principal access boundary policy + to delete. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + etag (str): + Optional. The etag of the principal access + boundary policy. If this is provided, it must + match the server's etag. + validate_only (bool): + Optional. If set, validate the request and + preview the deletion, but do not actually post + it. + force (bool): + Optional. If set to true, the request will + force the deletion of the policy even if the + policy is referenced in policy bindings. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListPrincipalAccessBoundaryPoliciesRequest(proto.Message): + r"""Request message for ListPrincipalAccessBoundaryPolicies + method. + + Attributes: + parent (str): + Required. The parent resource, which owns the collection of + principal access boundary policies. + + Format: + ``organizations/{organization_id}/locations/{location}`` + page_size (int): + Optional. The maximum number of principal + access boundary policies to return. The service + may return fewer than this value. + + If unspecified, at most 50 principal access + boundary policies will be returned. The maximum + value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListPrincipalAccessBoundaryPolicies`` call. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListPrincipalAccessBoundaryPolicies`` must match the call + that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPrincipalAccessBoundaryPoliciesResponse(proto.Message): + r"""Response message for ListPrincipalAccessBoundaryPolicies + method. + + Attributes: + principal_access_boundary_policies (MutableSequence[google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicy]): + The principal access boundary policies from + the specified parent. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + principal_access_boundary_policies: MutableSequence[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchPrincipalAccessBoundaryPolicyBindingsRequest(proto.Message): + r"""Request message for + SearchPrincipalAccessBoundaryPolicyBindings rpc. + + Attributes: + name (str): + Required. The name of the principal access boundary policy. + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + page_size (int): + Optional. The maximum number of policy + bindings to return. The service may return fewer + than this value. + + If unspecified, at most 50 policy bindings will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``SearchPrincipalAccessBoundaryPolicyBindingsRequest`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``SearchPrincipalAccessBoundaryPolicyBindingsRequest`` must + match the call that provided the page token. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchPrincipalAccessBoundaryPolicyBindingsResponse(proto.Message): + r"""Response message for + SearchPrincipalAccessBoundaryPolicyBindings rpc. + + Attributes: + policy_bindings (MutableSequence[google.cloud.iam_v3.types.PolicyBinding]): + The policy bindings that reference the + specified policy. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + policy_bindings: MutableSequence[policy_binding_resources.PolicyBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/principal_access_boundary_policy_resources.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/principal_access_boundary_policy_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..a535f1f6e7d21c81c69192d5dc903fe3c12cd2e9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3/types/principal_access_boundary_policy_resources.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v3", + manifest={ + "PrincipalAccessBoundaryPolicy", + "PrincipalAccessBoundaryPolicyDetails", + "PrincipalAccessBoundaryPolicyRule", + }, +) + + +class PrincipalAccessBoundaryPolicy(proto.Message): + r"""An IAM principal access boundary policy resource. + + Attributes: + name (str): + Identifier. The resource name of the principal access + boundary policy. + + The following format is supported: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{policy_id}`` + uid (str): + Output only. The globally unique ID of the + principal access boundary policy. + etag (str): + Optional. The etag for the principal access + boundary. If this is provided on update, it must + match the server's etag. + display_name (str): + Optional. The description of the principal + access boundary policy. Must be less than or + equal to 63 characters. + annotations (MutableMapping[str, str]): + Optional. User defined annotations. See + https://google.aip.dev/148#annotations for more + details such as format and size limitations + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the principal + access boundary policy was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the principal + access boundary policy was most recently + updated. + details (google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicyDetails): + Optional. The details for the principal + access boundary policy. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + details: "PrincipalAccessBoundaryPolicyDetails" = proto.Field( + proto.MESSAGE, + number=8, + message="PrincipalAccessBoundaryPolicyDetails", + ) + + +class PrincipalAccessBoundaryPolicyDetails(proto.Message): + r"""Principal access boundary policy details + + Attributes: + rules (MutableSequence[google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicyRule]): + Required. A list of principal access boundary + policy rules. The number of rules in a policy is + limited to 500. + enforcement_version (str): + Optional. The version number (for example, ``1`` or + ``latest``) that indicates which permissions are able to be + blocked by the policy. If empty, the PAB policy version will + be set to the most recent version number at the time of the + policy's creation. + """ + + rules: MutableSequence["PrincipalAccessBoundaryPolicyRule"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="PrincipalAccessBoundaryPolicyRule", + ) + enforcement_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class PrincipalAccessBoundaryPolicyRule(proto.Message): + r"""Principal access boundary policy rule that defines the + resource boundary. + + Attributes: + description (str): + Optional. The description of the principal + access boundary policy rule. Must be less than + or equal to 256 characters. + resources (MutableSequence[str]): + Required. A list of Resource Manager resources. If a + resource is listed in the rule, then the rule applies for + that resource and its descendants. The number of resources + in a policy is limited to 500 across all rules in the + policy. + + The following resource types are supported: + + - Organizations, such as + ``//cloudresourcemanager.googleapis.com/organizations/123``. + - Folders, such as + ``//cloudresourcemanager.googleapis.com/folders/123``. + - Projects, such as + ``//cloudresourcemanager.googleapis.com/projects/123`` or + ``//cloudresourcemanager.googleapis.com/projects/my-project-id``. + effect (google.cloud.iam_v3.types.PrincipalAccessBoundaryPolicyRule.Effect): + Required. The access relationship of + principals to the resources in this rule. + """ + + class Effect(proto.Enum): + r"""An effect to describe the access relationship. + + Values: + EFFECT_UNSPECIFIED (0): + Effect unspecified. + ALLOW (1): + Allows access to the resources in this rule. + """ + + EFFECT_UNSPECIFIED = 0 + ALLOW = 1 + + description: str = proto.Field( + proto.STRING, + number=1, + ) + resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + effect: Effect = proto.Field( + proto.ENUM, + number=3, + enum=Effect, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20cbd036ab534462d7e1038d06a9579ccb780483 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/__init__.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.iam_v3beta import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.policy_bindings import PolicyBindingsAsyncClient, PolicyBindingsClient +from .services.principal_access_boundary_policies import ( + PrincipalAccessBoundaryPoliciesAsyncClient, + PrincipalAccessBoundaryPoliciesClient, +) +from .types.operation_metadata import OperationMetadata +from .types.policy_binding_resources import PolicyBinding +from .types.policy_bindings_service import ( + CreatePolicyBindingRequest, + DeletePolicyBindingRequest, + GetPolicyBindingRequest, + ListPolicyBindingsRequest, + ListPolicyBindingsResponse, + SearchTargetPolicyBindingsRequest, + SearchTargetPolicyBindingsResponse, + UpdatePolicyBindingRequest, +) +from .types.principal_access_boundary_policies_service import ( + CreatePrincipalAccessBoundaryPolicyRequest, + DeletePrincipalAccessBoundaryPolicyRequest, + GetPrincipalAccessBoundaryPolicyRequest, + ListPrincipalAccessBoundaryPoliciesRequest, + ListPrincipalAccessBoundaryPoliciesResponse, + SearchPrincipalAccessBoundaryPolicyBindingsRequest, + SearchPrincipalAccessBoundaryPolicyBindingsResponse, + UpdatePrincipalAccessBoundaryPolicyRequest, +) +from .types.principal_access_boundary_policy_resources import ( + PrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPolicyDetails, + PrincipalAccessBoundaryPolicyRule, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.iam_v3beta") # type: ignore + api_core.check_dependency_versions("google.cloud.iam_v3beta") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.iam_v3beta" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "PolicyBindingsAsyncClient", + "PrincipalAccessBoundaryPoliciesAsyncClient", + "CreatePolicyBindingRequest", + "CreatePrincipalAccessBoundaryPolicyRequest", + "DeletePolicyBindingRequest", + "DeletePrincipalAccessBoundaryPolicyRequest", + "GetPolicyBindingRequest", + "GetPrincipalAccessBoundaryPolicyRequest", + "ListPolicyBindingsRequest", + "ListPolicyBindingsResponse", + "ListPrincipalAccessBoundaryPoliciesRequest", + "ListPrincipalAccessBoundaryPoliciesResponse", + "OperationMetadata", + "PolicyBinding", + "PolicyBindingsClient", + "PrincipalAccessBoundaryPoliciesClient", + "PrincipalAccessBoundaryPolicy", + "PrincipalAccessBoundaryPolicyDetails", + "PrincipalAccessBoundaryPolicyRule", + "SearchPrincipalAccessBoundaryPolicyBindingsRequest", + "SearchPrincipalAccessBoundaryPolicyBindingsResponse", + "SearchTargetPolicyBindingsRequest", + "SearchTargetPolicyBindingsResponse", + "UpdatePolicyBindingRequest", + "UpdatePrincipalAccessBoundaryPolicyRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bcfb25e343249411bbd2365249d4a93f2325681f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/gapic_metadata.json @@ -0,0 +1,227 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_v3beta", + "protoPackage": "google.iam.v3beta", + "schema": "1.0", + "services": { + "PolicyBindings": { + "clients": { + "grpc": { + "libraryClient": "PolicyBindingsClient", + "rpcs": { + "CreatePolicyBinding": { + "methods": [ + "create_policy_binding" + ] + }, + "DeletePolicyBinding": { + "methods": [ + "delete_policy_binding" + ] + }, + "GetPolicyBinding": { + "methods": [ + "get_policy_binding" + ] + }, + "ListPolicyBindings": { + "methods": [ + "list_policy_bindings" + ] + }, + "SearchTargetPolicyBindings": { + "methods": [ + "search_target_policy_bindings" + ] + }, + "UpdatePolicyBinding": { + "methods": [ + "update_policy_binding" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyBindingsAsyncClient", + "rpcs": { + "CreatePolicyBinding": { + "methods": [ + "create_policy_binding" + ] + }, + "DeletePolicyBinding": { + "methods": [ + "delete_policy_binding" + ] + }, + "GetPolicyBinding": { + "methods": [ + "get_policy_binding" + ] + }, + "ListPolicyBindings": { + "methods": [ + "list_policy_bindings" + ] + }, + "SearchTargetPolicyBindings": { + "methods": [ + "search_target_policy_bindings" + ] + }, + "UpdatePolicyBinding": { + "methods": [ + "update_policy_binding" + ] + } + } + }, + "rest": { + "libraryClient": "PolicyBindingsClient", + "rpcs": { + "CreatePolicyBinding": { + "methods": [ + "create_policy_binding" + ] + }, + "DeletePolicyBinding": { + "methods": [ + "delete_policy_binding" + ] + }, + "GetPolicyBinding": { + "methods": [ + "get_policy_binding" + ] + }, + "ListPolicyBindings": { + "methods": [ + "list_policy_bindings" + ] + }, + "SearchTargetPolicyBindings": { + "methods": [ + "search_target_policy_bindings" + ] + }, + "UpdatePolicyBinding": { + "methods": [ + "update_policy_binding" + ] + } + } + } + } + }, + "PrincipalAccessBoundaryPolicies": { + "clients": { + "grpc": { + "libraryClient": "PrincipalAccessBoundaryPoliciesClient", + "rpcs": { + "CreatePrincipalAccessBoundaryPolicy": { + "methods": [ + "create_principal_access_boundary_policy" + ] + }, + "DeletePrincipalAccessBoundaryPolicy": { + "methods": [ + "delete_principal_access_boundary_policy" + ] + }, + "GetPrincipalAccessBoundaryPolicy": { + "methods": [ + "get_principal_access_boundary_policy" + ] + }, + "ListPrincipalAccessBoundaryPolicies": { + "methods": [ + "list_principal_access_boundary_policies" + ] + }, + "SearchPrincipalAccessBoundaryPolicyBindings": { + "methods": [ + "search_principal_access_boundary_policy_bindings" + ] + }, + "UpdatePrincipalAccessBoundaryPolicy": { + "methods": [ + "update_principal_access_boundary_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PrincipalAccessBoundaryPoliciesAsyncClient", + "rpcs": { + "CreatePrincipalAccessBoundaryPolicy": { + "methods": [ + "create_principal_access_boundary_policy" + ] + }, + "DeletePrincipalAccessBoundaryPolicy": { + "methods": [ + "delete_principal_access_boundary_policy" + ] + }, + "GetPrincipalAccessBoundaryPolicy": { + "methods": [ + "get_principal_access_boundary_policy" + ] + }, + "ListPrincipalAccessBoundaryPolicies": { + "methods": [ + "list_principal_access_boundary_policies" + ] + }, + "SearchPrincipalAccessBoundaryPolicyBindings": { + "methods": [ + "search_principal_access_boundary_policy_bindings" + ] + }, + "UpdatePrincipalAccessBoundaryPolicy": { + "methods": [ + "update_principal_access_boundary_policy" + ] + } + } + }, + "rest": { + "libraryClient": "PrincipalAccessBoundaryPoliciesClient", + "rpcs": { + "CreatePrincipalAccessBoundaryPolicy": { + "methods": [ + "create_principal_access_boundary_policy" + ] + }, + "DeletePrincipalAccessBoundaryPolicy": { + "methods": [ + "delete_principal_access_boundary_policy" + ] + }, + "GetPrincipalAccessBoundaryPolicy": { + "methods": [ + "get_principal_access_boundary_policy" + ] + }, + "ListPrincipalAccessBoundaryPolicies": { + "methods": [ + "list_principal_access_boundary_policies" + ] + }, + "SearchPrincipalAccessBoundaryPolicyBindings": { + "methods": [ + "search_principal_access_boundary_policy_bindings" + ] + }, + "UpdatePrincipalAccessBoundaryPolicy": { + "methods": [ + "update_principal_access_boundary_policy" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ced4e0faf0db10b4db3fe7272f7565ac981a13cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.22.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..a8a7868953e6d9dfddbfde34344e8bea208dcbf4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c244552a39da26a50dfdf4cca9afd4cf71323e5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PolicyBindingsAsyncClient +from .client import PolicyBindingsClient + +__all__ = ( + "PolicyBindingsClient", + "PolicyBindingsAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..46f846bc892dd744fe983173040ec3feed25b3c2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/async_client.py @@ -0,0 +1,1266 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3beta.services.policy_bindings import pagers +from google.cloud.iam_v3beta.types import ( + operation_metadata, + policy_binding_resources, + policy_bindings_service, +) + +from .client import PolicyBindingsClient +from .transports.base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport +from .transports.grpc_asyncio import PolicyBindingsGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PolicyBindingsAsyncClient: + """An interface for managing Identity and Access Management + (IAM) policy bindings. + """ + + _client: PolicyBindingsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PolicyBindingsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyBindingsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PolicyBindingsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PolicyBindingsClient._DEFAULT_UNIVERSE + + policy_binding_path = staticmethod(PolicyBindingsClient.policy_binding_path) + parse_policy_binding_path = staticmethod( + PolicyBindingsClient.parse_policy_binding_path + ) + common_billing_account_path = staticmethod( + PolicyBindingsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PolicyBindingsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(PolicyBindingsClient.common_folder_path) + parse_common_folder_path = staticmethod( + PolicyBindingsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + PolicyBindingsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + PolicyBindingsClient.parse_common_organization_path + ) + common_project_path = staticmethod(PolicyBindingsClient.common_project_path) + parse_common_project_path = staticmethod( + PolicyBindingsClient.parse_common_project_path + ) + common_location_path = staticmethod(PolicyBindingsClient.common_location_path) + parse_common_location_path = staticmethod( + PolicyBindingsClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsAsyncClient: The constructed client. + """ + sa_info_func = ( + PolicyBindingsClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(PolicyBindingsAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsAsyncClient: The constructed client. + """ + sa_file_func = ( + PolicyBindingsClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(PolicyBindingsAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PolicyBindingsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PolicyBindingsTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyBindingsTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PolicyBindingsClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PolicyBindingsTransport, Callable[..., PolicyBindingsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy bindings async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PolicyBindingsTransport,Callable[..., PolicyBindingsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PolicyBindingsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PolicyBindingsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3beta.PolicyBindingsAsyncClient`.", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.v3beta.PolicyBindings", + "credentialsType": None, + }, + ) + + async def create_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.CreatePolicyBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + policy_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_create_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + policy_binding = iam_v3beta.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3beta.CreatePolicyBindingRequest( + parent="parent_value", + policy_binding_id="policy_binding_id_value", + policy_binding=policy_binding, + ) + + # Make the request + operation = client.create_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.CreatePolicyBindingRequest, dict]]): + The request object. Request message for + CreatePolicyBinding method. + parent (:class:`str`): + Required. The parent resource where this policy binding + will be created. The binding parent is the closest + Resource Manager resource (project, folder or + organization) to the binding target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding (:class:`google.cloud.iam_v3beta.types.PolicyBinding`): + Required. The policy binding to + create. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding_id (:class:`str`): + Required. The ID to use for the policy binding, which + will become the final component of the policy binding's + resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``policy_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy_binding, policy_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.CreatePolicyBindingRequest): + request = policy_bindings_service.CreatePolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_binding is not None: + request.policy_binding = policy_binding + if policy_binding_id is not None: + request.policy_binding_id = policy_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.GetPolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_binding_resources.PolicyBinding: + r"""Gets a policy binding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_get_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.GetPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.GetPolicyBindingRequest, dict]]): + The request object. Request message for GetPolicyBinding + method. + name (:class:`str`): + Required. The name of the policy binding to retrieve. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.types.PolicyBinding: + IAM policy binding resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.GetPolicyBindingRequest): + request = policy_bindings_service.GetPolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.UpdatePolicyBindingRequest, dict] + ] = None, + *, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_update_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + policy_binding = iam_v3beta.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3beta.UpdatePolicyBindingRequest( + policy_binding=policy_binding, + ) + + # Make the request + operation = client.update_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.UpdatePolicyBindingRequest, dict]]): + The request object. Request message for + UpdatePolicyBinding method. + policy_binding (:class:`google.cloud.iam_v3beta.types.PolicyBinding`): + Required. The policy binding to update. + + The policy binding's ``name`` field is used to identify + the policy binding to update. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [policy_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.UpdatePolicyBindingRequest): + request = policy_bindings_service.UpdatePolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_binding is not None: + request.policy_binding = policy_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy_binding.name", request.policy_binding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.DeletePolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_delete_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.DeletePolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.DeletePolicyBindingRequest, dict]]): + The request object. Request message for + DeletePolicyBinding method. + name (:class:`str`): + Required. The name of the policy binding to delete. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.DeletePolicyBindingRequest): + request = policy_bindings_service.DeletePolicyBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.ListPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPolicyBindingsAsyncPager: + r"""Lists policy bindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_list_policy_bindings(): + # Create a client + client = iam_v3beta.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.ListPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.ListPolicyBindingsRequest, dict]]): + The request object. Request message for + ListPolicyBindings method. + parent (:class:`str`): + Required. The parent resource, which owns the collection + of policy bindings. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.policy_bindings.pagers.ListPolicyBindingsAsyncPager: + Response message for + ListPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.ListPolicyBindingsRequest): + request = policy_bindings_service.ListPolicyBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_target_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.SearchTargetPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + target: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchTargetPolicyBindingsAsyncPager: + r"""Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_search_target_policy_bindings(): + # Create a client + client = iam_v3beta.PolicyBindingsAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.SearchTargetPolicyBindingsRequest( + target="target_value", + parent="parent_value", + ) + + # Make the request + page_result = client.search_target_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsRequest, dict]]): + The request object. Request message for + SearchTargetPolicyBindings method. + parent (:class:`str`): + Required. The parent resource where this search will be + performed. This should be the nearest Resource Manager + resource (project, folder, or organization) to the + target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target (:class:`str`): + Required. The target resource, which is bound to the + policy in the binding. + + Format: + + - ``//iam.googleapis.com/locations/global/workforcePools/POOL_ID`` + - ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID`` + - ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + - ``//cloudresourcemanager.googleapis.com/projects/{project_number}`` + - ``//cloudresourcemanager.googleapis.com/folders/{folder_id}`` + - ``//cloudresourcemanager.googleapis.com/organizations/{organization_id}`` + + This corresponds to the ``target`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.policy_bindings.pagers.SearchTargetPolicyBindingsAsyncPager: + Response message for + SearchTargetPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, target] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, policy_bindings_service.SearchTargetPolicyBindingsRequest + ): + request = policy_bindings_service.SearchTargetPolicyBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if target is not None: + request.target = target + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_target_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchTargetPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PolicyBindingsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PolicyBindingsAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/client.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbc1c8de4121c52c97ab3a5986e1e128432588d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/client.py @@ -0,0 +1,1692 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3beta.services.policy_bindings import pagers +from google.cloud.iam_v3beta.types import ( + operation_metadata, + policy_binding_resources, + policy_bindings_service, +) + +from .transports.base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport +from .transports.grpc import PolicyBindingsGrpcTransport +from .transports.grpc_asyncio import PolicyBindingsGrpcAsyncIOTransport +from .transports.rest import PolicyBindingsRestTransport + + +class PolicyBindingsClientMeta(type): + """Metaclass for the PolicyBindings client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PolicyBindingsTransport]] + _transport_registry["grpc"] = PolicyBindingsGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyBindingsGrpcAsyncIOTransport + _transport_registry["rest"] = PolicyBindingsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PolicyBindingsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PolicyBindingsClient(metaclass=PolicyBindingsClientMeta): + """An interface for managing Identity and Access Management + (IAM) policy bindings. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PolicyBindingsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PolicyBindingsTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyBindingsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def policy_binding_path( + organization: str, + location: str, + policy_binding: str, + ) -> str: + """Returns a fully-qualified policy_binding string.""" + return "organizations/{organization}/locations/{location}/policyBindings/{policy_binding}".format( + organization=organization, + location=location, + policy_binding=policy_binding, + ) + + @staticmethod + def parse_policy_binding_path(path: str) -> Dict[str, str]: + """Parses a policy_binding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/policyBindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = PolicyBindingsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = PolicyBindingsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PolicyBindingsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PolicyBindingsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PolicyBindingsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PolicyBindingsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PolicyBindingsTransport, Callable[..., PolicyBindingsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy bindings client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PolicyBindingsTransport,Callable[..., PolicyBindingsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PolicyBindingsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PolicyBindingsClient._read_environment_variables() + ) + self._client_cert_source = PolicyBindingsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PolicyBindingsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, PolicyBindingsTransport) + if transport_provided: + # transport is a PolicyBindingsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PolicyBindingsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or PolicyBindingsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PolicyBindingsTransport], Callable[..., PolicyBindingsTransport] + ] = ( + PolicyBindingsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PolicyBindingsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3beta.PolicyBindingsClient`.", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.v3beta.PolicyBindings", + "credentialsType": None, + }, + ) + + def create_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.CreatePolicyBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + policy_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_create_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsClient() + + # Initialize request argument(s) + policy_binding = iam_v3beta.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3beta.CreatePolicyBindingRequest( + parent="parent_value", + policy_binding_id="policy_binding_id_value", + policy_binding=policy_binding, + ) + + # Make the request + operation = client.create_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.CreatePolicyBindingRequest, dict]): + The request object. Request message for + CreatePolicyBinding method. + parent (str): + Required. The parent resource where this policy binding + will be created. The binding parent is the closest + Resource Manager resource (project, folder or + organization) to the binding target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding (google.cloud.iam_v3beta.types.PolicyBinding): + Required. The policy binding to + create. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_binding_id (str): + Required. The ID to use for the policy binding, which + will become the final component of the policy binding's + resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``policy_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, policy_binding, policy_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.CreatePolicyBindingRequest): + request = policy_bindings_service.CreatePolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_binding is not None: + request.policy_binding = policy_binding + if policy_binding_id is not None: + request.policy_binding_id = policy_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.GetPolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_binding_resources.PolicyBinding: + r"""Gets a policy binding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_get_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3beta.GetPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.GetPolicyBindingRequest, dict]): + The request object. Request message for GetPolicyBinding + method. + name (str): + Required. The name of the policy binding to retrieve. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.types.PolicyBinding: + IAM policy binding resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.GetPolicyBindingRequest): + request = policy_bindings_service.GetPolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.UpdatePolicyBindingRequest, dict] + ] = None, + *, + policy_binding: Optional[policy_binding_resources.PolicyBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_update_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsClient() + + # Initialize request argument(s) + policy_binding = iam_v3beta.PolicyBinding() + policy_binding.target.principal_set = "principal_set_value" + policy_binding.policy = "policy_value" + + request = iam_v3beta.UpdatePolicyBindingRequest( + policy_binding=policy_binding, + ) + + # Make the request + operation = client.update_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.UpdatePolicyBindingRequest, dict]): + The request object. Request message for + UpdatePolicyBinding method. + policy_binding (google.cloud.iam_v3beta.types.PolicyBinding): + Required. The policy binding to update. + + The policy binding's ``name`` field is used to identify + the policy binding to update. + + This corresponds to the ``policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PolicyBinding` IAM + policy binding resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [policy_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.UpdatePolicyBindingRequest): + request = policy_bindings_service.UpdatePolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_binding is not None: + request.policy_binding = policy_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("policy_binding.name", request.policy_binding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + policy_binding_resources.PolicyBinding, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_policy_binding( + self, + request: Optional[ + Union[policy_bindings_service.DeletePolicyBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_delete_policy_binding(): + # Create a client + client = iam_v3beta.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3beta.DeletePolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.DeletePolicyBindingRequest, dict]): + The request object. Request message for + DeletePolicyBinding method. + name (str): + Required. The name of the policy binding to delete. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.DeletePolicyBindingRequest): + request = policy_bindings_service.DeletePolicyBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_policy_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.ListPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPolicyBindingsPager: + r"""Lists policy bindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_list_policy_bindings(): + # Create a client + client = iam_v3beta.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3beta.ListPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.ListPolicyBindingsRequest, dict]): + The request object. Request message for + ListPolicyBindings method. + parent (str): + Required. The parent resource, which owns the collection + of policy bindings. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.policy_bindings.pagers.ListPolicyBindingsPager: + Response message for + ListPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, policy_bindings_service.ListPolicyBindingsRequest): + request = policy_bindings_service.ListPolicyBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_policy_bindings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_target_policy_bindings( + self, + request: Optional[ + Union[policy_bindings_service.SearchTargetPolicyBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + target: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchTargetPolicyBindingsPager: + r"""Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_search_target_policy_bindings(): + # Create a client + client = iam_v3beta.PolicyBindingsClient() + + # Initialize request argument(s) + request = iam_v3beta.SearchTargetPolicyBindingsRequest( + target="target_value", + parent="parent_value", + ) + + # Make the request + page_result = client.search_target_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsRequest, dict]): + The request object. Request message for + SearchTargetPolicyBindings method. + parent (str): + Required. The parent resource where this search will be + performed. This should be the nearest Resource Manager + resource (project, folder, or organization) to the + target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target (str): + Required. The target resource, which is bound to the + policy in the binding. + + Format: + + - ``//iam.googleapis.com/locations/global/workforcePools/POOL_ID`` + - ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID`` + - ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + - ``//cloudresourcemanager.googleapis.com/projects/{project_number}`` + - ``//cloudresourcemanager.googleapis.com/folders/{folder_id}`` + - ``//cloudresourcemanager.googleapis.com/organizations/{organization_id}`` + + This corresponds to the ``target`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.policy_bindings.pagers.SearchTargetPolicyBindingsPager: + Response message for + SearchTargetPolicyBindings method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, target] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, policy_bindings_service.SearchTargetPolicyBindingsRequest + ): + request = policy_bindings_service.SearchTargetPolicyBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if target is not None: + request.target = target + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.search_target_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchTargetPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PolicyBindingsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PolicyBindingsClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..92935e339382d16e95b6f53e4a4db7deaf659d34 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/pagers.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + policy_bindings_service, +) + + +class ListPolicyBindingsPager: + """A pager for iterating through ``list_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.ListPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.ListPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., policy_bindings_service.ListPolicyBindingsResponse], + request: policy_bindings_service.ListPolicyBindingsRequest, + response: policy_bindings_service.ListPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.ListPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.ListPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.ListPolicyBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policy_bindings_service.ListPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy_binding_resources.PolicyBinding]: + for page in self.pages: + yield from page.policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPolicyBindingsAsyncPager: + """A pager for iterating through ``list_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.ListPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.ListPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[policy_bindings_service.ListPolicyBindingsResponse] + ], + request: policy_bindings_service.ListPolicyBindingsRequest, + response: policy_bindings_service.ListPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.ListPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.ListPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.ListPolicyBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[policy_bindings_service.ListPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy_binding_resources.PolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchTargetPolicyBindingsPager: + """A pager for iterating through ``search_target_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchTargetPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., policy_bindings_service.SearchTargetPolicyBindingsResponse + ], + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + response: policy_bindings_service.SearchTargetPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.SearchTargetPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[policy_bindings_service.SearchTargetPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy_binding_resources.PolicyBinding]: + for page in self.pages: + yield from page.policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchTargetPolicyBindingsAsyncPager: + """A pager for iterating through ``search_target_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchTargetPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[policy_bindings_service.SearchTargetPolicyBindingsResponse] + ], + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + response: policy_bindings_service.SearchTargetPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.SearchTargetPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = policy_bindings_service.SearchTargetPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[policy_bindings_service.SearchTargetPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy_binding_resources.PolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6d5224bc4cc964ac54c8e531309984814978f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PolicyBindingsTransport +from .grpc import PolicyBindingsGrpcTransport +from .grpc_asyncio import PolicyBindingsGrpcAsyncIOTransport +from .rest import PolicyBindingsRestInterceptor, PolicyBindingsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyBindingsTransport]] +_transport_registry["grpc"] = PolicyBindingsGrpcTransport +_transport_registry["grpc_asyncio"] = PolicyBindingsGrpcAsyncIOTransport +_transport_registry["rest"] = PolicyBindingsRestTransport + +__all__ = ( + "PolicyBindingsTransport", + "PolicyBindingsGrpcTransport", + "PolicyBindingsGrpcAsyncIOTransport", + "PolicyBindingsRestTransport", + "PolicyBindingsRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f28baab156da614907d061bfcfe9ef0d4f15009e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/base.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3beta import gapic_version as package_version +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + policy_bindings_service, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PolicyBindingsTransport(abc.ABC): + """Abstract transport class for PolicyBindings.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_policy_binding: gapic_v1.method.wrap_method( + self.create_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.get_policy_binding: gapic_v1.method.wrap_method( + self.get_policy_binding, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy_binding: gapic_v1.method.wrap_method( + self.update_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_policy_binding: gapic_v1.method.wrap_method( + self.delete_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.list_policy_bindings: gapic_v1.method.wrap_method( + self.list_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_target_policy_bindings: gapic_v1.method.wrap_method( + self.search_target_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + Union[ + policy_binding_resources.PolicyBinding, + Awaitable[policy_binding_resources.PolicyBinding], + ], + ]: + raise NotImplementedError() + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + Union[ + policy_bindings_service.ListPolicyBindingsResponse, + Awaitable[policy_bindings_service.ListPolicyBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + Union[ + policy_bindings_service.SearchTargetPolicyBindingsResponse, + Awaitable[policy_bindings_service.SearchTargetPolicyBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PolicyBindingsTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..0a5cb039af841bb1eaf1439dc9c145586c7739e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/grpc.py @@ -0,0 +1,562 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + policy_bindings_service, +) + +from .base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PolicyBindingsGrpcTransport(PolicyBindingsTransport): + """gRPC backend transport for PolicyBindings. + + An interface for managing Identity and Access Management + (IAM) policy bindings. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create policy binding method over gRPC. + + Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + Returns: + Callable[[~.CreatePolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy_binding" not in self._stubs: + self._stubs["create_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/CreatePolicyBinding", + request_serializer=policy_bindings_service.CreatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy_binding"] + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + policy_binding_resources.PolicyBinding, + ]: + r"""Return a callable for the get policy binding method over gRPC. + + Gets a policy binding. + + Returns: + Callable[[~.GetPolicyBindingRequest], + ~.PolicyBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy_binding" not in self._stubs: + self._stubs["get_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/GetPolicyBinding", + request_serializer=policy_bindings_service.GetPolicyBindingRequest.serialize, + response_deserializer=policy_binding_resources.PolicyBinding.deserialize, + ) + return self._stubs["get_policy_binding"] + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update policy binding method over gRPC. + + Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + Returns: + Callable[[~.UpdatePolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy_binding" not in self._stubs: + self._stubs["update_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/UpdatePolicyBinding", + request_serializer=policy_bindings_service.UpdatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy_binding"] + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete policy binding method over gRPC. + + Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + Returns: + Callable[[~.DeletePolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy_binding" not in self._stubs: + self._stubs["delete_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/DeletePolicyBinding", + request_serializer=policy_bindings_service.DeletePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy_binding"] + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + policy_bindings_service.ListPolicyBindingsResponse, + ]: + r"""Return a callable for the list policy bindings method over gRPC. + + Lists policy bindings. + + Returns: + Callable[[~.ListPolicyBindingsRequest], + ~.ListPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policy_bindings" not in self._stubs: + self._stubs["list_policy_bindings"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/ListPolicyBindings", + request_serializer=policy_bindings_service.ListPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.ListPolicyBindingsResponse.deserialize, + ) + return self._stubs["list_policy_bindings"] + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + policy_bindings_service.SearchTargetPolicyBindingsResponse, + ]: + r"""Return a callable for the search target policy bindings method over gRPC. + + Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + Returns: + Callable[[~.SearchTargetPolicyBindingsRequest], + ~.SearchTargetPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_target_policy_bindings" not in self._stubs: + self._stubs["search_target_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/SearchTargetPolicyBindings", + request_serializer=policy_bindings_service.SearchTargetPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.SearchTargetPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_target_policy_bindings"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PolicyBindingsGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..5598743b10ed8adb5772ebee083c02cacbe93f5f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/grpc_asyncio.py @@ -0,0 +1,645 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + policy_bindings_service, +) + +from .base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport +from .grpc import PolicyBindingsGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PolicyBindingsGrpcAsyncIOTransport(PolicyBindingsTransport): + """gRPC AsyncIO backend transport for PolicyBindings. + + An interface for managing Identity and Access Management + (IAM) policy bindings. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create policy binding method over gRPC. + + Creates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is created, the + policy is applied to the target. + + Returns: + Callable[[~.CreatePolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_policy_binding" not in self._stubs: + self._stubs["create_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/CreatePolicyBinding", + request_serializer=policy_bindings_service.CreatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy_binding"] + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + Awaitable[policy_binding_resources.PolicyBinding], + ]: + r"""Return a callable for the get policy binding method over gRPC. + + Gets a policy binding. + + Returns: + Callable[[~.GetPolicyBindingRequest], + Awaitable[~.PolicyBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_policy_binding" not in self._stubs: + self._stubs["get_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/GetPolicyBinding", + request_serializer=policy_bindings_service.GetPolicyBindingRequest.serialize, + response_deserializer=policy_binding_resources.PolicyBinding.deserialize, + ) + return self._stubs["get_policy_binding"] + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update policy binding method over gRPC. + + Updates a policy binding and returns a long-running + operation. Callers will need the IAM permissions on the + policy and target in the binding to update, and the IAM + permission to remove the existing policy from the + binding. Target is immutable and cannot be updated. Once + the binding is updated, the new policy is applied to the + target. + + Returns: + Callable[[~.UpdatePolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_policy_binding" not in self._stubs: + self._stubs["update_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/UpdatePolicyBinding", + request_serializer=policy_bindings_service.UpdatePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_policy_binding"] + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete policy binding method over gRPC. + + Deletes a policy binding and returns a long-running + operation. Callers will need the IAM permissions on both + the policy and target. Once the binding is deleted, the + policy no longer applies to the target. + + Returns: + Callable[[~.DeletePolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_policy_binding" not in self._stubs: + self._stubs["delete_policy_binding"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/DeletePolicyBinding", + request_serializer=policy_bindings_service.DeletePolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy_binding"] + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + Awaitable[policy_bindings_service.ListPolicyBindingsResponse], + ]: + r"""Return a callable for the list policy bindings method over gRPC. + + Lists policy bindings. + + Returns: + Callable[[~.ListPolicyBindingsRequest], + Awaitable[~.ListPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_policy_bindings" not in self._stubs: + self._stubs["list_policy_bindings"] = self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/ListPolicyBindings", + request_serializer=policy_bindings_service.ListPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.ListPolicyBindingsResponse.deserialize, + ) + return self._stubs["list_policy_bindings"] + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + Awaitable[policy_bindings_service.SearchTargetPolicyBindingsResponse], + ]: + r"""Return a callable for the search target policy bindings method over gRPC. + + Search policy bindings by target. Returns all policy + binding objects bound directly to target. + + Returns: + Callable[[~.SearchTargetPolicyBindingsRequest], + Awaitable[~.SearchTargetPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_target_policy_bindings" not in self._stubs: + self._stubs["search_target_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PolicyBindings/SearchTargetPolicyBindings", + request_serializer=policy_bindings_service.SearchTargetPolicyBindingsRequest.serialize, + response_deserializer=policy_bindings_service.SearchTargetPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_target_policy_bindings"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_policy_binding: self._wrap_method( + self.create_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.get_policy_binding: self._wrap_method( + self.get_policy_binding, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_policy_binding: self._wrap_method( + self.update_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_policy_binding: self._wrap_method( + self.delete_policy_binding, + default_timeout=30.0, + client_info=client_info, + ), + self.list_policy_bindings: self._wrap_method( + self.list_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_target_policy_bindings: self._wrap_method( + self.search_target_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("PolicyBindingsGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..464d3948d20f15d411cdca32052f922e38c1de31 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/rest.py @@ -0,0 +1,1720 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + policy_bindings_service, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePolicyBindingsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PolicyBindingsRestInterceptor: + """Interceptor for PolicyBindings. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PolicyBindingsRestTransport. + + .. code-block:: python + class MyCustomPolicyBindingsInterceptor(PolicyBindingsRestInterceptor): + def pre_create_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_target_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_target_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PolicyBindingsRestTransport(interceptor=MyCustomPolicyBindingsInterceptor()) + client = PolicyBindingsClient(transport=transport) + + + """ + + def pre_create_policy_binding( + self, + request: policy_bindings_service.CreatePolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.CreatePolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_create_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_policy_binding + + DEPRECATED. Please use the `post_create_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_create_policy_binding` interceptor runs + before the `post_create_policy_binding_with_metadata` interceptor. + """ + return response + + def post_create_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_create_policy_binding_with_metadata` + interceptor in new development instead of the `post_create_policy_binding` interceptor. + When both interceptors are used, this `post_create_policy_binding_with_metadata` interceptor runs after the + `post_create_policy_binding` interceptor. The (possibly modified) response returned by + `post_create_policy_binding` will be passed to + `post_create_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_delete_policy_binding( + self, + request: policy_bindings_service.DeletePolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.DeletePolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_delete_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_policy_binding + + DEPRECATED. Please use the `post_delete_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_delete_policy_binding` interceptor runs + before the `post_delete_policy_binding_with_metadata` interceptor. + """ + return response + + def post_delete_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_delete_policy_binding_with_metadata` + interceptor in new development instead of the `post_delete_policy_binding` interceptor. + When both interceptors are used, this `post_delete_policy_binding_with_metadata` interceptor runs after the + `post_delete_policy_binding` interceptor. The (possibly modified) response returned by + `post_delete_policy_binding` will be passed to + `post_delete_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_get_policy_binding( + self, + request: policy_bindings_service.GetPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.GetPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_get_policy_binding( + self, response: policy_binding_resources.PolicyBinding + ) -> policy_binding_resources.PolicyBinding: + """Post-rpc interceptor for get_policy_binding + + DEPRECATED. Please use the `post_get_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_get_policy_binding` interceptor runs + before the `post_get_policy_binding_with_metadata` interceptor. + """ + return response + + def post_get_policy_binding_with_metadata( + self, + response: policy_binding_resources.PolicyBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_binding_resources.PolicyBinding, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_get_policy_binding_with_metadata` + interceptor in new development instead of the `post_get_policy_binding` interceptor. + When both interceptors are used, this `post_get_policy_binding_with_metadata` interceptor runs after the + `post_get_policy_binding` interceptor. The (possibly modified) response returned by + `post_get_policy_binding` will be passed to + `post_get_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_list_policy_bindings( + self, + request: policy_bindings_service.ListPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.ListPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_list_policy_bindings( + self, response: policy_bindings_service.ListPolicyBindingsResponse + ) -> policy_bindings_service.ListPolicyBindingsResponse: + """Post-rpc interceptor for list_policy_bindings + + DEPRECATED. Please use the `post_list_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_list_policy_bindings` interceptor runs + before the `post_list_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_list_policy_bindings_with_metadata( + self, + response: policy_bindings_service.ListPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.ListPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_list_policy_bindings_with_metadata` + interceptor in new development instead of the `post_list_policy_bindings` interceptor. + When both interceptors are used, this `post_list_policy_bindings_with_metadata` interceptor runs after the + `post_list_policy_bindings` interceptor. The (possibly modified) response returned by + `post_list_policy_bindings` will be passed to + `post_list_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_search_target_policy_bindings( + self, + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.SearchTargetPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for search_target_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_search_target_policy_bindings( + self, response: policy_bindings_service.SearchTargetPolicyBindingsResponse + ) -> policy_bindings_service.SearchTargetPolicyBindingsResponse: + """Post-rpc interceptor for search_target_policy_bindings + + DEPRECATED. Please use the `post_search_target_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_search_target_policy_bindings` interceptor runs + before the `post_search_target_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_search_target_policy_bindings_with_metadata( + self, + response: policy_bindings_service.SearchTargetPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.SearchTargetPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for search_target_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_search_target_policy_bindings_with_metadata` + interceptor in new development instead of the `post_search_target_policy_bindings` interceptor. + When both interceptors are used, this `post_search_target_policy_bindings_with_metadata` interceptor runs after the + `post_search_target_policy_bindings` interceptor. The (possibly modified) response returned by + `post_search_target_policy_bindings` will be passed to + `post_search_target_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_update_policy_binding( + self, + request: policy_bindings_service.UpdatePolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + policy_bindings_service.UpdatePolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_update_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_policy_binding + + DEPRECATED. Please use the `post_update_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. This `post_update_policy_binding` interceptor runs + before the `post_update_policy_binding_with_metadata` interceptor. + """ + return response + + def post_update_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PolicyBindings server but before it is returned to user code. + + We recommend only using this `post_update_policy_binding_with_metadata` + interceptor in new development instead of the `post_update_policy_binding` interceptor. + When both interceptors are used, this `post_update_policy_binding_with_metadata` interceptor runs after the + `post_update_policy_binding` interceptor. The (possibly modified) response returned by + `post_update_policy_binding` will be passed to + `post_update_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the PolicyBindings server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the PolicyBindings server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PolicyBindingsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PolicyBindingsRestInterceptor + + +class PolicyBindingsRestTransport(_BasePolicyBindingsRestTransport): + """REST backend synchronous transport for PolicyBindings. + + An interface for managing Identity and Access Management + (IAM) policy bindings. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PolicyBindingsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[PolicyBindingsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PolicyBindingsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePolicyBinding( + _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.CreatePolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: policy_bindings_service.CreatePolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.CreatePolicyBindingRequest): + The request object. Request message for + CreatePolicyBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_create_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_transcoded_request( + http_options, request + ) + + body = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.CreatePolicyBinding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "CreatePolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._CreatePolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsClient.create_policy_binding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "CreatePolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePolicyBinding( + _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.DeletePolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.DeletePolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.DeletePolicyBindingRequest): + The request object. Request message for + DeletePolicyBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_delete_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.DeletePolicyBinding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "DeletePolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._DeletePolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsClient.delete_policy_binding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "DeletePolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPolicyBinding( + _BasePolicyBindingsRestTransport._BaseGetPolicyBinding, PolicyBindingsRestStub + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.GetPolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.GetPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_binding_resources.PolicyBinding: + r"""Call the get policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.GetPolicyBindingRequest): + The request object. Request message for GetPolicyBinding + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy_binding_resources.PolicyBinding: + IAM policy binding resource. + """ + + http_options = _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_get_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.GetPolicyBinding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "GetPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._GetPolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_binding_resources.PolicyBinding() + pb_resp = policy_binding_resources.PolicyBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = policy_binding_resources.PolicyBinding.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsClient.get_policy_binding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "GetPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPolicyBindings( + _BasePolicyBindingsRestTransport._BaseListPolicyBindings, PolicyBindingsRestStub + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.ListPolicyBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.ListPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_bindings_service.ListPolicyBindingsResponse: + r"""Call the list policy bindings method over HTTP. + + Args: + request (~.policy_bindings_service.ListPolicyBindingsRequest): + The request object. Request message for + ListPolicyBindings method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy_bindings_service.ListPolicyBindingsResponse: + Response message for + ListPolicyBindings method. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_http_options() + + request, metadata = self._interceptor.pre_list_policy_bindings( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.ListPolicyBindings", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "ListPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._ListPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_bindings_service.ListPolicyBindingsResponse() + pb_resp = policy_bindings_service.ListPolicyBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_policy_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_policy_bindings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + policy_bindings_service.ListPolicyBindingsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsClient.list_policy_bindings", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "ListPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchTargetPolicyBindings( + _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.SearchTargetPolicyBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: policy_bindings_service.SearchTargetPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_bindings_service.SearchTargetPolicyBindingsResponse: + r"""Call the search target policy + bindings method over HTTP. + + Args: + request (~.policy_bindings_service.SearchTargetPolicyBindingsRequest): + The request object. Request message for + SearchTargetPolicyBindings method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.policy_bindings_service.SearchTargetPolicyBindingsResponse: + Response message for + SearchTargetPolicyBindings method. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_http_options() + + request, metadata = self._interceptor.pre_search_target_policy_bindings( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.SearchTargetPolicyBindings", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "SearchTargetPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + PolicyBindingsRestTransport._SearchTargetPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_bindings_service.SearchTargetPolicyBindingsResponse() + pb_resp = policy_bindings_service.SearchTargetPolicyBindingsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_search_target_policy_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_search_target_policy_bindings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = policy_bindings_service.SearchTargetPolicyBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsClient.search_target_policy_bindings", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "SearchTargetPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePolicyBinding( + _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding, + PolicyBindingsRestStub, + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.UpdatePolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: policy_bindings_service.UpdatePolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update policy binding method over HTTP. + + Args: + request (~.policy_bindings_service.UpdatePolicyBindingRequest): + The request object. Request message for + UpdatePolicyBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_http_options() + + request, metadata = self._interceptor.pre_update_policy_binding( + request, metadata + ) + transcoded_request = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_transcoded_request( + http_options, request + ) + + body = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.UpdatePolicyBinding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "UpdatePolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._UpdatePolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_policy_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsClient.update_policy_binding", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "UpdatePolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.CreatePolicyBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.DeletePolicyBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.GetPolicyBindingRequest], + policy_binding_resources.PolicyBinding, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.ListPolicyBindingsRequest], + policy_bindings_service.ListPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPolicyBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_target_policy_bindings( + self, + ) -> Callable[ + [policy_bindings_service.SearchTargetPolicyBindingsRequest], + policy_bindings_service.SearchTargetPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchTargetPolicyBindings( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_policy_binding( + self, + ) -> Callable[ + [policy_bindings_service.UpdatePolicyBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePolicyBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BasePolicyBindingsRestTransport._BaseGetOperation, PolicyBindingsRestStub + ): + def __hash__(self): + return hash("PolicyBindingsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BasePolicyBindingsRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BasePolicyBindingsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePolicyBindingsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PolicyBindingsClient.GetOperation", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PolicyBindingsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PolicyBindingsAsyncClient.GetOperation", + extra={ + "serviceName": "google.iam.v3beta.PolicyBindings", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PolicyBindingsRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..d752e75a4d4912984859e305f589de9817385ce5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/policy_bindings/transports/rest_base.py @@ -0,0 +1,489 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + policy_bindings_service, +) + +from .base import DEFAULT_CLIENT_INFO, PolicyBindingsTransport + + +class _BasePolicyBindingsRestTransport(PolicyBindingsTransport): + """Base REST backend transport for PolicyBindings. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "policyBindingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta/{parent=projects/*/locations/*}/policyBindings", + "body": "policy_binding", + }, + { + "method": "post", + "uri": "/v3beta/{parent=folders/*/locations/*}/policyBindings", + "body": "policy_binding", + }, + { + "method": "post", + "uri": "/v3beta/{parent=organizations/*/locations/*}/policyBindings", + "body": "policy_binding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.CreatePolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseCreatePolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3beta/{name=projects/*/locations/*/policyBindings/*}", + }, + { + "method": "delete", + "uri": "/v3beta/{name=folders/*/locations/*/policyBindings/*}", + }, + { + "method": "delete", + "uri": "/v3beta/{name=organizations/*/locations/*/policyBindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.DeletePolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseDeletePolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{name=projects/*/locations/*/policyBindings/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=folders/*/locations/*/policyBindings/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/policyBindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.GetPolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseGetPolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{parent=projects/*/locations/*}/policyBindings", + }, + { + "method": "get", + "uri": "/v3beta/{parent=folders/*/locations/*}/policyBindings", + }, + { + "method": "get", + "uri": "/v3beta/{parent=organizations/*/locations/*}/policyBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.ListPolicyBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseListPolicyBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchTargetPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "target": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{parent=projects/*/locations/*}/policyBindings:searchTargetPolicyBindings", + }, + { + "method": "get", + "uri": "/v3beta/{parent=folders/*/locations/*}/policyBindings:searchTargetPolicyBindings", + }, + { + "method": "get", + "uri": "/v3beta/{parent=organizations/*/locations/*}/policyBindings:searchTargetPolicyBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.SearchTargetPolicyBindingsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseSearchTargetPolicyBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3beta/{policy_binding.name=projects/*/locations/*/policyBindings/*}", + "body": "policy_binding", + }, + { + "method": "patch", + "uri": "/v3beta/{policy_binding.name=folders/*/locations/*/policyBindings/*}", + "body": "policy_binding", + }, + { + "method": "patch", + "uri": "/v3beta/{policy_binding.name=organizations/*/locations/*/policyBindings/*}", + "body": "policy_binding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = policy_bindings_service.UpdatePolicyBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePolicyBindingsRestTransport._BaseUpdatePolicyBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePolicyBindingsRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8835ba99fe94123093e9fed0964f5e92eb77db43 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PrincipalAccessBoundaryPoliciesAsyncClient +from .client import PrincipalAccessBoundaryPoliciesClient + +__all__ = ( + "PrincipalAccessBoundaryPoliciesClient", + "PrincipalAccessBoundaryPoliciesAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..83794c2bbec53684215fbb8c5cfff7df5ee78245 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/async_client.py @@ -0,0 +1,1301 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3beta.services.principal_access_boundary_policies import pagers +from google.cloud.iam_v3beta.types import ( + operation_metadata, + policy_binding_resources, + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .client import PrincipalAccessBoundaryPoliciesClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + PrincipalAccessBoundaryPoliciesTransport, +) +from .transports.grpc_asyncio import PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PrincipalAccessBoundaryPoliciesAsyncClient: + """Manages Identity and Access Management (IAM) principal access + boundary policies. + """ + + _client: PrincipalAccessBoundaryPoliciesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PrincipalAccessBoundaryPoliciesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PrincipalAccessBoundaryPoliciesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + PrincipalAccessBoundaryPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = PrincipalAccessBoundaryPoliciesClient._DEFAULT_UNIVERSE + + policy_binding_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.policy_binding_path + ) + parse_policy_binding_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_policy_binding_path + ) + principal_access_boundary_policy_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.principal_access_boundary_policy_path + ) + parse_principal_access_boundary_policy_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_principal_access_boundary_policy_path + ) + common_billing_account_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_organization_path + ) + common_project_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_project_path + ) + parse_common_project_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_project_path + ) + common_location_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.common_location_path + ) + parse_common_location_path = staticmethod( + PrincipalAccessBoundaryPoliciesClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesAsyncClient: The constructed client. + """ + sa_info_func = ( + PrincipalAccessBoundaryPoliciesClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + PrincipalAccessBoundaryPoliciesAsyncClient, info, *args, **kwargs + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesAsyncClient: The constructed client. + """ + sa_file_func = ( + PrincipalAccessBoundaryPoliciesClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + PrincipalAccessBoundaryPoliciesAsyncClient, filename, *args, **kwargs + ) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PrincipalAccessBoundaryPoliciesClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> PrincipalAccessBoundaryPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PrincipalAccessBoundaryPoliciesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PrincipalAccessBoundaryPoliciesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + PrincipalAccessBoundaryPoliciesTransport, + Callable[..., PrincipalAccessBoundaryPoliciesTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the principal access boundary policies async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PrincipalAccessBoundaryPoliciesTransport,Callable[..., PrincipalAccessBoundaryPoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PrincipalAccessBoundaryPoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PrincipalAccessBoundaryPoliciesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient`.", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "credentialsType": None, + }, + ) + + async def create_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + principal_access_boundary_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a principal access boundary policy, and + returns a long running operation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_create_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.CreatePrincipalAccessBoundaryPolicyRequest( + parent="parent_value", + principal_access_boundary_policy_id="principal_access_boundary_policy_id_value", + ) + + # Make the request + operation = client.create_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.CreatePrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + CreatePrincipalAccessBoundaryPolicyRequest + method. + parent (:class:`str`): + Required. The parent resource where this principal + access boundary policy will be created. Only + organizations are supported. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy (:class:`google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy`): + Required. The principal access + boundary policy to create. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy_id (:class:`str`): + Required. The ID to use for the principal access + boundary policy, which will become the final component + of the principal access boundary policy's resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``principal_access_boundary_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + principal_access_boundary_policy, + principal_access_boundary_policy_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = principal_access_boundary_policy + if principal_access_boundary_policy_id is not None: + request.principal_access_boundary_policy_id = ( + principal_access_boundary_policy_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + r"""Gets a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_get_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.GetPrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_principal_access_boundary_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.GetPrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + GetPrincipalAccessBoundaryPolicy method. + name (:class:`str`): + Required. The name of the principal access boundary + policy to retrieve. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy: + An IAM principal access boundary + policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_update_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.UpdatePrincipalAccessBoundaryPolicyRequest( + ) + + # Make the request + operation = client.update_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.UpdatePrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + UpdatePrincipalAccessBoundaryPolicy + method. + principal_access_boundary_policy (:class:`google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy`): + Required. The principal access boundary policy to + update. + + The principal access boundary policy's ``name`` field is + used to identify the policy to update. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [principal_access_boundary_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = principal_access_boundary_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "principal_access_boundary_policy.name", + request.principal_access_boundary_policy.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_delete_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.DeletePrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.DeletePrincipalAccessBoundaryPolicyRequest, dict]]): + The request object. Request message for + DeletePrincipalAccessBoundaryPolicy + method. + name (:class:`str`): + Required. The name of the principal access boundary + policy to delete. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_principal_access_boundary_policies( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPrincipalAccessBoundaryPoliciesAsyncPager: + r"""Lists principal access boundary policies. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_list_principal_access_boundary_policies(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.ListPrincipalAccessBoundaryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_principal_access_boundary_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesRequest, dict]]): + The request object. Request message for + ListPrincipalAccessBoundaryPolicies + method. + parent (:class:`str`): + Required. The parent resource, which owns the collection + of principal access boundary policies. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.principal_access_boundary_policies.pagers.ListPrincipalAccessBoundaryPoliciesAsyncPager: + Response message for + ListPrincipalAccessBoundaryPolicies + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + ): + request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_principal_access_boundary_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPrincipalAccessBoundaryPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_principal_access_boundary_policy_bindings( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager: + r"""Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + async def sample_search_principal_access_boundary_policy_bindings(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient() + + # Initialize request argument(s) + request = iam_v3beta.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + name="name_value", + ) + + # Make the request + page_result = client.search_principal_access_boundary_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest, dict]]): + The request object. Request message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + name (:class:`str`): + Required. The name of the principal access boundary + policy. Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.principal_access_boundary_policies.pagers.SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager: + Response message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + ): + request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_principal_access_boundary_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PrincipalAccessBoundaryPoliciesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PrincipalAccessBoundaryPoliciesAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/client.py new file mode 100644 index 0000000000000000000000000000000000000000..08d34d9da505938f844a6d5ddc3fd508728d7bcf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/client.py @@ -0,0 +1,1760 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v3beta.services.principal_access_boundary_policies import pagers +from google.cloud.iam_v3beta.types import ( + operation_metadata, + policy_binding_resources, + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + PrincipalAccessBoundaryPoliciesTransport, +) +from .transports.grpc import PrincipalAccessBoundaryPoliciesGrpcTransport +from .transports.grpc_asyncio import PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport +from .transports.rest import PrincipalAccessBoundaryPoliciesRestTransport + + +class PrincipalAccessBoundaryPoliciesClientMeta(type): + """Metaclass for the PrincipalAccessBoundaryPolicies client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PrincipalAccessBoundaryPoliciesTransport]] + _transport_registry["grpc"] = PrincipalAccessBoundaryPoliciesGrpcTransport + _transport_registry["grpc_asyncio"] = ( + PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport + ) + _transport_registry["rest"] = PrincipalAccessBoundaryPoliciesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PrincipalAccessBoundaryPoliciesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PrincipalAccessBoundaryPoliciesClient( + metaclass=PrincipalAccessBoundaryPoliciesClientMeta +): + """Manages Identity and Access Management (IAM) principal access + boundary policies. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PrincipalAccessBoundaryPoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PrincipalAccessBoundaryPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + PrincipalAccessBoundaryPoliciesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def policy_binding_path( + organization: str, + location: str, + policy_binding: str, + ) -> str: + """Returns a fully-qualified policy_binding string.""" + return "organizations/{organization}/locations/{location}/policyBindings/{policy_binding}".format( + organization=organization, + location=location, + policy_binding=policy_binding, + ) + + @staticmethod + def parse_policy_binding_path(path: str) -> Dict[str, str]: + """Parses a policy_binding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/policyBindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def principal_access_boundary_policy_path( + organization: str, + location: str, + principal_access_boundary_policy: str, + ) -> str: + """Returns a fully-qualified principal_access_boundary_policy string.""" + return "organizations/{organization}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy}".format( + organization=organization, + location=location, + principal_access_boundary_policy=principal_access_boundary_policy, + ) + + @staticmethod + def parse_principal_access_boundary_policy_path(path: str) -> Dict[str, str]: + """Parses a principal_access_boundary_policy path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/principalAccessBoundaryPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ( + PrincipalAccessBoundaryPoliciesClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ( + PrincipalAccessBoundaryPoliciesClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PrincipalAccessBoundaryPoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PrincipalAccessBoundaryPoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + PrincipalAccessBoundaryPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PrincipalAccessBoundaryPoliciesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + PrincipalAccessBoundaryPoliciesTransport, + Callable[..., PrincipalAccessBoundaryPoliciesTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the principal access boundary policies client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PrincipalAccessBoundaryPoliciesTransport,Callable[..., PrincipalAccessBoundaryPoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PrincipalAccessBoundaryPoliciesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PrincipalAccessBoundaryPoliciesClient._read_environment_variables() + ) + self._client_cert_source = ( + PrincipalAccessBoundaryPoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + PrincipalAccessBoundaryPoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, PrincipalAccessBoundaryPoliciesTransport + ) + if transport_provided: + # transport is a PrincipalAccessBoundaryPoliciesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PrincipalAccessBoundaryPoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or PrincipalAccessBoundaryPoliciesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PrincipalAccessBoundaryPoliciesTransport], + Callable[..., PrincipalAccessBoundaryPoliciesTransport], + ] = ( + PrincipalAccessBoundaryPoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., PrincipalAccessBoundaryPoliciesTransport], transport + ) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient`.", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "credentialsType": None, + }, + ) + + def create_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + principal_access_boundary_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a principal access boundary policy, and + returns a long running operation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_create_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3beta.CreatePrincipalAccessBoundaryPolicyRequest( + parent="parent_value", + principal_access_boundary_policy_id="principal_access_boundary_policy_id_value", + ) + + # Make the request + operation = client.create_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.CreatePrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + CreatePrincipalAccessBoundaryPolicyRequest + method. + parent (str): + Required. The parent resource where this principal + access boundary policy will be created. Only + organizations are supported. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy (google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy): + Required. The principal access + boundary policy to create. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + principal_access_boundary_policy_id (str): + Required. The ID to use for the principal access + boundary policy, which will become the final component + of the principal access boundary policy's resource name. + + This value must start with a lowercase letter followed + by up to 62 lowercase letters, numbers, hyphens, or + dots. Pattern, /[a-z][a-z0-9-.]{2,62}/. + + This corresponds to the ``principal_access_boundary_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + principal_access_boundary_policy, + principal_access_boundary_policy_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = ( + principal_access_boundary_policy + ) + if principal_access_boundary_policy_id is not None: + request.principal_access_boundary_policy_id = ( + principal_access_boundary_policy_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + r"""Gets a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_get_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3beta.GetPrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_principal_access_boundary_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.GetPrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + GetPrincipalAccessBoundaryPolicy method. + name (str): + Required. The name of the principal access boundary + policy to retrieve. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy: + An IAM principal access boundary + policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + principal_access_boundary_policy: Optional[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_update_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3beta.UpdatePrincipalAccessBoundaryPolicyRequest( + ) + + # Make the request + operation = client.update_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.UpdatePrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + UpdatePrincipalAccessBoundaryPolicy + method. + principal_access_boundary_policy (google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy): + Required. The principal access boundary policy to + update. + + The principal access boundary policy's ``name`` field is + used to identify the policy to update. + + This corresponds to the ``principal_access_boundary_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy` + An IAM principal access boundary policy resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [principal_access_boundary_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if principal_access_boundary_policy is not None: + request.principal_access_boundary_policy = ( + principal_access_boundary_policy + ) + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "principal_access_boundary_policy.name", + request.principal_access_boundary_policy.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_principal_access_boundary_policy( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a principal access boundary policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_delete_principal_access_boundary_policy(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3beta.DeletePrincipalAccessBoundaryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_principal_access_boundary_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.DeletePrincipalAccessBoundaryPolicyRequest, dict]): + The request object. Request message for + DeletePrincipalAccessBoundaryPolicy + method. + name (str): + Required. The name of the principal access boundary + policy to delete. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + ): + request = principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_principal_access_boundary_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=operation_metadata.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_principal_access_boundary_policies( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPrincipalAccessBoundaryPoliciesPager: + r"""Lists principal access boundary policies. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_list_principal_access_boundary_policies(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3beta.ListPrincipalAccessBoundaryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_principal_access_boundary_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesRequest, dict]): + The request object. Request message for + ListPrincipalAccessBoundaryPolicies + method. + parent (str): + Required. The parent resource, which owns the collection + of principal access boundary policies. + + Format: + ``organizations/{organization_id}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.principal_access_boundary_policies.pagers.ListPrincipalAccessBoundaryPoliciesPager: + Response message for + ListPrincipalAccessBoundaryPolicies + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + ): + request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_principal_access_boundary_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPrincipalAccessBoundaryPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_principal_access_boundary_policy_bindings( + self, + request: Optional[ + Union[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchPrincipalAccessBoundaryPolicyBindingsPager: + r"""Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_v3beta + + def sample_search_principal_access_boundary_policy_bindings(): + # Create a client + client = iam_v3beta.PrincipalAccessBoundaryPoliciesClient() + + # Initialize request argument(s) + request = iam_v3beta.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + name="name_value", + ) + + # Make the request + page_result = client.search_principal_access_boundary_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest, dict]): + The request object. Request message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + name (str): + Required. The name of the principal access boundary + policy. Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.iam_v3beta.services.principal_access_boundary_policies.pagers.SearchPrincipalAccessBoundaryPolicyBindingsPager: + Response message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + ): + request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.search_principal_access_boundary_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchPrincipalAccessBoundaryPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PrincipalAccessBoundaryPoliciesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PrincipalAccessBoundaryPoliciesClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..5927f0680f1ca687642b318d6602d8f30877998a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/pagers.py @@ -0,0 +1,405 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + + +class ListPrincipalAccessBoundaryPoliciesPager: + """A pager for iterating through ``list_principal_access_boundary_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``principal_access_boundary_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPrincipalAccessBoundaryPolicies`` requests and continue to iterate + through the ``principal_access_boundary_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ], + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__( + self, + ) -> Iterator[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ]: + for page in self.pages: + yield from page.principal_access_boundary_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPrincipalAccessBoundaryPoliciesAsyncPager: + """A pager for iterating through ``list_principal_access_boundary_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``principal_access_boundary_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPrincipalAccessBoundaryPolicies`` requests and continue to iterate + through the ``principal_access_boundary_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ], + ], + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.ListPrincipalAccessBoundaryPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ]: + async def async_generator(): + async for page in self.pages: + for response in page.principal_access_boundary_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchPrincipalAccessBoundaryPolicyBindingsPager: + """A pager for iterating through ``search_principal_access_boundary_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchPrincipalAccessBoundaryPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ], + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[policy_binding_resources.PolicyBinding]: + for page in self.pages: + yield from page.policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchPrincipalAccessBoundaryPolicyBindingsAsyncPager: + """A pager for iterating through ``search_principal_access_boundary_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchPrincipalAccessBoundaryPolicyBindings`` requests and continue to iterate + through the ``policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ], + ], + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsRequest): + The initial request object. + response (google.cloud.iam_v3beta.types.SearchPrincipalAccessBoundaryPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[policy_binding_resources.PolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..572b487008f51f9fa2f5ceaf3928c1e83129cd1e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PrincipalAccessBoundaryPoliciesTransport +from .grpc import PrincipalAccessBoundaryPoliciesGrpcTransport +from .grpc_asyncio import PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport +from .rest import ( + PrincipalAccessBoundaryPoliciesRestInterceptor, + PrincipalAccessBoundaryPoliciesRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PrincipalAccessBoundaryPoliciesTransport]] +_transport_registry["grpc"] = PrincipalAccessBoundaryPoliciesGrpcTransport +_transport_registry["grpc_asyncio"] = ( + PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport +) +_transport_registry["rest"] = PrincipalAccessBoundaryPoliciesRestTransport + +__all__ = ( + "PrincipalAccessBoundaryPoliciesTransport", + "PrincipalAccessBoundaryPoliciesGrpcTransport", + "PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport", + "PrincipalAccessBoundaryPoliciesRestTransport", + "PrincipalAccessBoundaryPoliciesRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..66a82bcb3dff282692d77a24333b45a03f7dbf7c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/base.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iam_v3beta import gapic_version as package_version +from google.cloud.iam_v3beta.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PrincipalAccessBoundaryPoliciesTransport(abc.ABC): + """Abstract transport class for PrincipalAccessBoundaryPolicies.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.create_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.get_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.get_principal_access_boundary_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.update_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_principal_access_boundary_policy: gapic_v1.method.wrap_method( + self.delete_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.list_principal_access_boundary_policies: gapic_v1.method.wrap_method( + self.list_principal_access_boundary_policies, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_principal_access_boundary_policy_bindings: gapic_v1.method.wrap_method( + self.search_principal_access_boundary_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + Union[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + Awaitable[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ], + ], + ]: + raise NotImplementedError() + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + Union[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + Awaitable[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + Union[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + Awaitable[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PrincipalAccessBoundaryPoliciesTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..66769bc1b90dd3970e28edc68cc130ce99b3cd3e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/grpc.py @@ -0,0 +1,585 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.iam_v3beta.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO, PrincipalAccessBoundaryPoliciesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PrincipalAccessBoundaryPoliciesGrpcTransport( + PrincipalAccessBoundaryPoliciesTransport +): + """gRPC backend transport for PrincipalAccessBoundaryPolicies. + + Manages Identity and Access Management (IAM) principal access + boundary policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the create principal access + boundary policy method over gRPC. + + Creates a principal access boundary policy, and + returns a long running operation. + + Returns: + Callable[[~.CreatePrincipalAccessBoundaryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_principal_access_boundary_policy" not in self._stubs: + self._stubs["create_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/CreatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_principal_access_boundary_policy"] + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ]: + r"""Return a callable for the get principal access boundary + policy method over gRPC. + + Gets a principal access boundary policy. + + Returns: + Callable[[~.GetPrincipalAccessBoundaryPolicyRequest], + ~.PrincipalAccessBoundaryPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_principal_access_boundary_policy" not in self._stubs: + self._stubs["get_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/GetPrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.deserialize, + ) + ) + return self._stubs["get_principal_access_boundary_policy"] + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the update principal access + boundary policy method over gRPC. + + Updates a principal access boundary policy. + + Returns: + Callable[[~.UpdatePrincipalAccessBoundaryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_principal_access_boundary_policy" not in self._stubs: + self._stubs["update_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/UpdatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_principal_access_boundary_policy"] + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete principal access + boundary policy method over gRPC. + + Deletes a principal access boundary policy. + + Returns: + Callable[[~.DeletePrincipalAccessBoundaryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_principal_access_boundary_policy" not in self._stubs: + self._stubs["delete_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/DeletePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_principal_access_boundary_policy"] + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ]: + r"""Return a callable for the list principal access boundary + policies method over gRPC. + + Lists principal access boundary policies. + + Returns: + Callable[[~.ListPrincipalAccessBoundaryPoliciesRequest], + ~.ListPrincipalAccessBoundaryPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_principal_access_boundary_policies" not in self._stubs: + self._stubs["list_principal_access_boundary_policies"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/ListPrincipalAccessBoundaryPolicies", + request_serializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_principal_access_boundary_policies"] + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ]: + r"""Return a callable for the search principal access + boundary policy bindings method over gRPC. + + Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + Returns: + Callable[[~.SearchPrincipalAccessBoundaryPolicyBindingsRequest], + ~.SearchPrincipalAccessBoundaryPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_principal_access_boundary_policy_bindings" not in self._stubs: + self._stubs["search_principal_access_boundary_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/SearchPrincipalAccessBoundaryPolicyBindings", + request_serializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_principal_access_boundary_policy_bindings"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PrincipalAccessBoundaryPoliciesGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3cc22b22304fd108225b21623311c55b00a376 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/grpc_asyncio.py @@ -0,0 +1,671 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_v3beta.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO, PrincipalAccessBoundaryPoliciesTransport +from .grpc import PrincipalAccessBoundaryPoliciesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport( + PrincipalAccessBoundaryPoliciesTransport +): + """gRPC AsyncIO backend transport for PrincipalAccessBoundaryPolicies. + + Manages Identity and Access Management (IAM) principal access + boundary policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create principal access + boundary policy method over gRPC. + + Creates a principal access boundary policy, and + returns a long running operation. + + Returns: + Callable[[~.CreatePrincipalAccessBoundaryPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_principal_access_boundary_policy" not in self._stubs: + self._stubs["create_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/CreatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_principal_access_boundary_policy"] + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + Awaitable[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ], + ]: + r"""Return a callable for the get principal access boundary + policy method over gRPC. + + Gets a principal access boundary policy. + + Returns: + Callable[[~.GetPrincipalAccessBoundaryPolicyRequest], + Awaitable[~.PrincipalAccessBoundaryPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_principal_access_boundary_policy" not in self._stubs: + self._stubs["get_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/GetPrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.deserialize, + ) + ) + return self._stubs["get_principal_access_boundary_policy"] + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update principal access + boundary policy method over gRPC. + + Updates a principal access boundary policy. + + Returns: + Callable[[~.UpdatePrincipalAccessBoundaryPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_principal_access_boundary_policy" not in self._stubs: + self._stubs["update_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/UpdatePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_principal_access_boundary_policy"] + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete principal access + boundary policy method over gRPC. + + Deletes a principal access boundary policy. + + Returns: + Callable[[~.DeletePrincipalAccessBoundaryPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_principal_access_boundary_policy" not in self._stubs: + self._stubs["delete_principal_access_boundary_policy"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/DeletePrincipalAccessBoundaryPolicy", + request_serializer=principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_principal_access_boundary_policy"] + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + Awaitable[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse + ], + ]: + r"""Return a callable for the list principal access boundary + policies method over gRPC. + + Lists principal access boundary policies. + + Returns: + Callable[[~.ListPrincipalAccessBoundaryPoliciesRequest], + Awaitable[~.ListPrincipalAccessBoundaryPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_principal_access_boundary_policies" not in self._stubs: + self._stubs["list_principal_access_boundary_policies"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/ListPrincipalAccessBoundaryPolicies", + request_serializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_principal_access_boundary_policies"] + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + Awaitable[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse + ], + ]: + r"""Return a callable for the search principal access + boundary policy bindings method over gRPC. + + Returns all policy bindings that bind a specific + policy if a user has searchPolicyBindings permission on + that policy. + + Returns: + Callable[[~.SearchPrincipalAccessBoundaryPolicyBindingsRequest], + Awaitable[~.SearchPrincipalAccessBoundaryPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_principal_access_boundary_policy_bindings" not in self._stubs: + self._stubs["search_principal_access_boundary_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.iam.v3beta.PrincipalAccessBoundaryPolicies/SearchPrincipalAccessBoundaryPolicyBindings", + request_serializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest.serialize, + response_deserializer=principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["search_principal_access_boundary_policy_bindings"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_principal_access_boundary_policy: self._wrap_method( + self.create_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.get_principal_access_boundary_policy: self._wrap_method( + self.get_principal_access_boundary_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_principal_access_boundary_policy: self._wrap_method( + self.update_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_principal_access_boundary_policy: self._wrap_method( + self.delete_principal_access_boundary_policy, + default_timeout=30.0, + client_info=client_info, + ), + self.list_principal_access_boundary_policies: self._wrap_method( + self.list_principal_access_boundary_policies, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_principal_access_boundary_policy_bindings: self._wrap_method( + self.search_principal_access_boundary_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("PrincipalAccessBoundaryPoliciesGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..26fe003561c77cdda914f89b3b189d3d0aeff0b6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/rest.py @@ -0,0 +1,1806 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.iam_v3beta.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePrincipalAccessBoundaryPoliciesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PrincipalAccessBoundaryPoliciesRestInterceptor: + """Interceptor for PrincipalAccessBoundaryPolicies. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PrincipalAccessBoundaryPoliciesRestTransport. + + .. code-block:: python + class MyCustomPrincipalAccessBoundaryPoliciesInterceptor(PrincipalAccessBoundaryPoliciesRestInterceptor): + def pre_create_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_principal_access_boundary_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_principal_access_boundary_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_principal_access_boundary_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_principal_access_boundary_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_principal_access_boundary_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_principal_access_boundary_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PrincipalAccessBoundaryPoliciesRestTransport(interceptor=MyCustomPrincipalAccessBoundaryPoliciesInterceptor()) + client = PrincipalAccessBoundaryPoliciesClient(transport=transport) + + + """ + + def pre_create_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_create_principal_access_boundary_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_principal_access_boundary_policy + + DEPRECATED. Please use the `post_create_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_create_principal_access_boundary_policy` interceptor runs + before the `post_create_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_create_principal_access_boundary_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_create_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_create_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_create_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_create_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_create_principal_access_boundary_policy` will be passed to + `post_create_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_delete_principal_access_boundary_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_principal_access_boundary_policy + + DEPRECATED. Please use the `post_delete_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_delete_principal_access_boundary_policy` interceptor runs + before the `post_delete_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_delete_principal_access_boundary_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_delete_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_delete_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_delete_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_delete_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_delete_principal_access_boundary_policy` will be passed to + `post_delete_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_get_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_get_principal_access_boundary_policy( + self, + response: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + """Post-rpc interceptor for get_principal_access_boundary_policy + + DEPRECATED. Please use the `post_get_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_get_principal_access_boundary_policy` interceptor runs + before the `post_get_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_get_principal_access_boundary_policy_with_metadata( + self, + response: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_get_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_get_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_get_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_get_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_get_principal_access_boundary_policy` will be passed to + `post_get_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_list_principal_access_boundary_policies( + self, + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_principal_access_boundary_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_list_principal_access_boundary_policies( + self, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ) -> principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse: + """Post-rpc interceptor for list_principal_access_boundary_policies + + DEPRECATED. Please use the `post_list_principal_access_boundary_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_list_principal_access_boundary_policies` interceptor runs + before the `post_list_principal_access_boundary_policies_with_metadata` interceptor. + """ + return response + + def post_list_principal_access_boundary_policies_with_metadata( + self, + response: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_principal_access_boundary_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_list_principal_access_boundary_policies_with_metadata` + interceptor in new development instead of the `post_list_principal_access_boundary_policies` interceptor. + When both interceptors are used, this `post_list_principal_access_boundary_policies_with_metadata` interceptor runs after the + `post_list_principal_access_boundary_policies` interceptor. The (possibly modified) response returned by + `post_list_principal_access_boundary_policies` will be passed to + `post_list_principal_access_boundary_policies_with_metadata`. + """ + return response, metadata + + def pre_search_principal_access_boundary_policy_bindings( + self, + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for search_principal_access_boundary_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_search_principal_access_boundary_policy_bindings( + self, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ) -> principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse: + """Post-rpc interceptor for search_principal_access_boundary_policy_bindings + + DEPRECATED. Please use the `post_search_principal_access_boundary_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_search_principal_access_boundary_policy_bindings` interceptor runs + before the `post_search_principal_access_boundary_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_search_principal_access_boundary_policy_bindings_with_metadata( + self, + response: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for search_principal_access_boundary_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_search_principal_access_boundary_policy_bindings_with_metadata` + interceptor in new development instead of the `post_search_principal_access_boundary_policy_bindings` interceptor. + When both interceptors are used, this `post_search_principal_access_boundary_policy_bindings_with_metadata` interceptor runs after the + `post_search_principal_access_boundary_policy_bindings` interceptor. The (possibly modified) response returned by + `post_search_principal_access_boundary_policy_bindings` will be passed to + `post_search_principal_access_boundary_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_update_principal_access_boundary_policy( + self, + request: principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_principal_access_boundary_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_update_principal_access_boundary_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_principal_access_boundary_policy + + DEPRECATED. Please use the `post_update_principal_access_boundary_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. This `post_update_principal_access_boundary_policy` interceptor runs + before the `post_update_principal_access_boundary_policy_with_metadata` interceptor. + """ + return response + + def post_update_principal_access_boundary_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_principal_access_boundary_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the PrincipalAccessBoundaryPolicies server but before it is returned to user code. + + We recommend only using this `post_update_principal_access_boundary_policy_with_metadata` + interceptor in new development instead of the `post_update_principal_access_boundary_policy` interceptor. + When both interceptors are used, this `post_update_principal_access_boundary_policy_with_metadata` interceptor runs after the + `post_update_principal_access_boundary_policy` interceptor. The (possibly modified) response returned by + `post_update_principal_access_boundary_policy` will be passed to + `post_update_principal_access_boundary_policy_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrincipalAccessBoundaryPolicies server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the PrincipalAccessBoundaryPolicies server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PrincipalAccessBoundaryPoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PrincipalAccessBoundaryPoliciesRestInterceptor + + +class PrincipalAccessBoundaryPoliciesRestTransport( + _BasePrincipalAccessBoundaryPoliciesRestTransport +): + """REST backend synchronous transport for PrincipalAccessBoundaryPolicies. + + Manages Identity and Access Management (IAM) principal access + boundary policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PrincipalAccessBoundaryPoliciesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[PrincipalAccessBoundaryPoliciesRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or PrincipalAccessBoundaryPoliciesRestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.CreatePrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + CreatePrincipalAccessBoundaryPolicyRequest + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_create_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + body = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.CreatePrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "CreatePrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._CreatePrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.create_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "CreatePrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.DeletePrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + DeletePrincipalAccessBoundaryPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_delete_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.DeletePrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "DeletePrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._DeletePrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.delete_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "DeletePrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.GetPrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + r"""Call the get principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + GetPrincipalAccessBoundaryPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy: + An IAM principal access boundary + policy resource. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.GetPrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "GetPrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._GetPrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy() + pb_resp = principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.get_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "GetPrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPrincipalAccessBoundaryPolicies( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.ListPrincipalAccessBoundaryPolicies" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse: + r"""Call the list principal access + boundary policies method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest): + The request object. Request message for + ListPrincipalAccessBoundaryPolicies + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse: + Response message for + ListPrincipalAccessBoundaryPolicies + method. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_http_options() + + request, metadata = ( + self._interceptor.pre_list_principal_access_boundary_policies( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.ListPrincipalAccessBoundaryPolicies", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "ListPrincipalAccessBoundaryPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._ListPrincipalAccessBoundaryPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse() + pb_resp = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_principal_access_boundary_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_principal_access_boundary_policies_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.list_principal_access_boundary_policies", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "ListPrincipalAccessBoundaryPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchPrincipalAccessBoundaryPolicyBindings( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.SearchPrincipalAccessBoundaryPolicyBindings" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse: + r"""Call the search principal access + boundary policy bindings method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest): + The request object. Request message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse: + Response message for + SearchPrincipalAccessBoundaryPolicyBindings + rpc. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_http_options() + + request, metadata = ( + self._interceptor.pre_search_principal_access_boundary_policy_bindings( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.SearchPrincipalAccessBoundaryPolicyBindings", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "SearchPrincipalAccessBoundaryPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._SearchPrincipalAccessBoundaryPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse() + pb_resp = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_search_principal_access_boundary_policy_bindings( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_search_principal_access_boundary_policy_bindings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.search_principal_access_boundary_policy_bindings", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "SearchPrincipalAccessBoundaryPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePrincipalAccessBoundaryPolicy( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash( + "PrincipalAccessBoundaryPoliciesRestTransport.UpdatePrincipalAccessBoundaryPolicy" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update principal access + boundary policy method over HTTP. + + Args: + request (~.principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest): + The request object. Request message for + UpdatePrincipalAccessBoundaryPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_http_options() + + request, metadata = ( + self._interceptor.pre_update_principal_access_boundary_policy( + request, metadata + ) + ) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_transcoded_request( + http_options, request + ) + + body = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.UpdatePrincipalAccessBoundaryPolicy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "UpdatePrincipalAccessBoundaryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._UpdatePrincipalAccessBoundaryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_principal_access_boundary_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_principal_access_boundary_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.update_principal_access_boundary_policy", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "UpdatePrincipalAccessBoundaryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest + ], + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_principal_access_boundary_policies( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest + ], + principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPrincipalAccessBoundaryPolicies( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def search_principal_access_boundary_policy_bindings( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest + ], + principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchPrincipalAccessBoundaryPolicyBindings( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_principal_access_boundary_policy( + self, + ) -> Callable[ + [ + principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest + ], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePrincipalAccessBoundaryPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation, + PrincipalAccessBoundaryPoliciesRestStub, + ): + def __hash__(self): + return hash("PrincipalAccessBoundaryPoliciesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.iam_v3beta.PrincipalAccessBoundaryPoliciesClient.GetOperation", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PrincipalAccessBoundaryPoliciesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.iam_v3beta.PrincipalAccessBoundaryPoliciesAsyncClient.GetOperation", + extra={ + "serviceName": "google.iam.v3beta.PrincipalAccessBoundaryPolicies", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PrincipalAccessBoundaryPoliciesRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..d71e8b97753f5978c6ccb7ebe2e74f956c5c512e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/services/principal_access_boundary_policies/transports/rest_base.py @@ -0,0 +1,447 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.iam_v3beta.types import ( + principal_access_boundary_policies_service, + principal_access_boundary_policy_resources, +) + +from .base import DEFAULT_CLIENT_INFO, PrincipalAccessBoundaryPoliciesTransport + + +class _BasePrincipalAccessBoundaryPoliciesRestTransport( + PrincipalAccessBoundaryPoliciesTransport +): + """Base REST backend transport for PrincipalAccessBoundaryPolicies. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "principalAccessBoundaryPolicyId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3beta/{parent=organizations/*/locations/*}/principalAccessBoundaryPolicies", + "body": "principal_access_boundary_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.CreatePrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseCreatePrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3beta/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.DeletePrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseDeletePrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.GetPrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseGetPrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPrincipalAccessBoundaryPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{parent=organizations/*/locations/*}/principalAccessBoundaryPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.ListPrincipalAccessBoundaryPoliciesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseListPrincipalAccessBoundaryPolicies._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchPrincipalAccessBoundaryPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}:searchPolicyBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.SearchPrincipalAccessBoundaryPolicyBindingsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseSearchPrincipalAccessBoundaryPolicyBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePrincipalAccessBoundaryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3beta/{principal_access_boundary_policy.name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", + "body": "principal_access_boundary_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = principal_access_boundary_policies_service.UpdatePrincipalAccessBoundaryPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrincipalAccessBoundaryPoliciesRestTransport._BaseUpdatePrincipalAccessBoundaryPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=folders/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3beta/{name=organizations/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePrincipalAccessBoundaryPoliciesRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0caa3a5e8dd71799f29ece5293ff01b722d4fa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/__init__.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .operation_metadata import ( + OperationMetadata, +) +from .policy_binding_resources import ( + PolicyBinding, +) +from .policy_bindings_service import ( + CreatePolicyBindingRequest, + DeletePolicyBindingRequest, + GetPolicyBindingRequest, + ListPolicyBindingsRequest, + ListPolicyBindingsResponse, + SearchTargetPolicyBindingsRequest, + SearchTargetPolicyBindingsResponse, + UpdatePolicyBindingRequest, +) +from .principal_access_boundary_policies_service import ( + CreatePrincipalAccessBoundaryPolicyRequest, + DeletePrincipalAccessBoundaryPolicyRequest, + GetPrincipalAccessBoundaryPolicyRequest, + ListPrincipalAccessBoundaryPoliciesRequest, + ListPrincipalAccessBoundaryPoliciesResponse, + SearchPrincipalAccessBoundaryPolicyBindingsRequest, + SearchPrincipalAccessBoundaryPolicyBindingsResponse, + UpdatePrincipalAccessBoundaryPolicyRequest, +) +from .principal_access_boundary_policy_resources import ( + PrincipalAccessBoundaryPolicy, + PrincipalAccessBoundaryPolicyDetails, + PrincipalAccessBoundaryPolicyRule, +) + +__all__ = ( + "OperationMetadata", + "PolicyBinding", + "CreatePolicyBindingRequest", + "DeletePolicyBindingRequest", + "GetPolicyBindingRequest", + "ListPolicyBindingsRequest", + "ListPolicyBindingsResponse", + "SearchTargetPolicyBindingsRequest", + "SearchTargetPolicyBindingsResponse", + "UpdatePolicyBindingRequest", + "CreatePrincipalAccessBoundaryPolicyRequest", + "DeletePrincipalAccessBoundaryPolicyRequest", + "GetPrincipalAccessBoundaryPolicyRequest", + "ListPrincipalAccessBoundaryPoliciesRequest", + "ListPrincipalAccessBoundaryPoliciesResponse", + "SearchPrincipalAccessBoundaryPolicyBindingsRequest", + "SearchPrincipalAccessBoundaryPolicyBindingsResponse", + "UpdatePrincipalAccessBoundaryPolicyRequest", + "PrincipalAccessBoundaryPolicy", + "PrincipalAccessBoundaryPolicyDetails", + "PrincipalAccessBoundaryPolicyRule", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/operation_metadata.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/operation_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1928afb3d4dd127de398d2c8cf8d5aac8cfb2f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/operation_metadata.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v3beta", + manifest={ + "OperationMetadata", + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/policy_binding_resources.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/policy_binding_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..364ebe83c9b4fdbb09ed9e327c2295eb08a3fad0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/policy_binding_resources.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.expr_pb2 as expr_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v3beta", + manifest={ + "PolicyBinding", + }, +) + + +class PolicyBinding(proto.Message): + r"""IAM policy binding resource. + + Attributes: + name (str): + Identifier. The name of the policy binding, in the format + ``{binding_parent/locations/{location}/policyBindings/{policy_binding_id}``. + The binding parent is the closest Resource Manager resource + (project, folder, or organization) to the binding target. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + uid (str): + Output only. The globally unique ID of the + policy binding. Assigned when the policy binding + is created. + etag (str): + Optional. The etag for the policy binding. + If this is provided on update, it must match the + server's etag. + display_name (str): + Optional. The description of the policy + binding. Must be less than or equal to 63 + characters. + annotations (MutableMapping[str, str]): + Optional. User-defined annotations. See + https://google.aip.dev/148#annotations for more + details such as format and size limitations + target (google.cloud.iam_v3beta.types.PolicyBinding.Target): + Required. Immutable. Target is the full + resource name of the resource to which the + policy will be bound. Immutable once set. + policy_kind (google.cloud.iam_v3beta.types.PolicyBinding.PolicyKind): + Immutable. The kind of the policy to attach + in this binding. This field must be one of the + following: + + - Left empty (will be automatically set to the + policy kind) + - The input policy kind + policy (str): + Required. Immutable. The resource name of the + policy to be bound. The binding parent and + policy must belong to the same organization. + policy_uid (str): + Output only. The globally unique ID of the + policy to be bound. + condition (google.type.expr_pb2.Expr): + Optional. The condition to apply to the policy binding. When + set, the ``expression`` field in the ``Expr`` must include + from 1 to 10 subexpressions, joined by the "\|\|"(Logical + OR), "&&"(Logical AND) or "!"(Logical NOT) operators and + cannot contain more than 250 characters. + + The condition is currently only supported when bound to + policies of kind principal access boundary. + + When the bound policy is a principal access boundary policy, + the only supported attributes in any subexpression are + ``principal.type`` and ``principal.subject``. An example + expression is: "principal.type == + 'iam.googleapis.com/ServiceAccount'" or "principal.subject + == 'bob@example.com'". + + Allowed operations for ``principal.subject``: + + - ``principal.subject == `` + - ``principal.subject != `` + - ``principal.subject in []`` + - ``principal.subject.startsWith()`` + - ``principal.subject.endsWith()`` + + Allowed operations for ``principal.type``: + + - ``principal.type == `` + - ``principal.type != `` + - ``principal.type in []`` + + Supported principal types are Workspace, Workforce Pool, + Workload Pool and Service Account. Allowed string must be + one of: + + - iam.googleapis.com/WorkspaceIdentity + - iam.googleapis.com/WorkforcePoolIdentity + - iam.googleapis.com/WorkloadPoolIdentity + - iam.googleapis.com/ServiceAccount + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the policy binding + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the policy binding + was most recently updated. + """ + + class PolicyKind(proto.Enum): + r"""Different policy kinds supported in this binding. + + Values: + POLICY_KIND_UNSPECIFIED (0): + Unspecified policy kind; Not a valid state + PRINCIPAL_ACCESS_BOUNDARY (1): + Principal access boundary policy kind + """ + + POLICY_KIND_UNSPECIFIED = 0 + PRINCIPAL_ACCESS_BOUNDARY = 1 + + class Target(proto.Message): + r"""Target is the full resource name of the resource to which the + policy will be bound. Immutable once set. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + principal_set (str): + Immutable. Full Resource Name used for principal access + boundary policy bindings. The principal set must be directly + parented by the policy binding's parent or same as the + parent if the target is a project/folder/organization. + + Examples: + + - For binding's parented by an organization: + + - Organization: + ``//cloudresourcemanager.googleapis.com/organizations/ORGANIZATION_ID`` + - Workforce Identity: + ``//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID`` + - Workspace Identity: + ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + + - For binding's parented by a folder: + + - Folder: + ``//cloudresourcemanager.googleapis.com/folders/FOLDER_ID`` + + - For binding's parented by a project: + + - Project: + + - ``//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER`` + - ``//cloudresourcemanager.googleapis.com/projects/PROJECT_ID`` + + - Workload Identity Pool: + ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/LOCATION/workloadIdentityPools/WORKLOAD_POOL_ID`` + + This field is a member of `oneof`_ ``target``. + """ + + principal_set: str = proto.Field( + proto.STRING, + number=1, + oneof="target", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + target: Target = proto.Field( + proto.MESSAGE, + number=6, + message=Target, + ) + policy_kind: PolicyKind = proto.Field( + proto.ENUM, + number=11, + enum=PolicyKind, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_uid: str = proto.Field( + proto.STRING, + number=12, + ) + condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=8, + message=expr_pb2.Expr, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/policy_bindings_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/policy_bindings_service.py new file mode 100644 index 0000000000000000000000000000000000000000..83de2fce724dd7091c2a0f267a3526fb83b5a874 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/policy_bindings_service.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.iam_v3beta.types import policy_binding_resources + +__protobuf__ = proto.module( + package="google.iam.v3beta", + manifest={ + "CreatePolicyBindingRequest", + "GetPolicyBindingRequest", + "UpdatePolicyBindingRequest", + "DeletePolicyBindingRequest", + "ListPolicyBindingsRequest", + "ListPolicyBindingsResponse", + "SearchTargetPolicyBindingsRequest", + "SearchTargetPolicyBindingsResponse", + }, +) + + +class CreatePolicyBindingRequest(proto.Message): + r"""Request message for CreatePolicyBinding method. + + Attributes: + parent (str): + Required. The parent resource where this policy binding will + be created. The binding parent is the closest Resource + Manager resource (project, folder or organization) to the + binding target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + policy_binding_id (str): + Required. The ID to use for the policy binding, which will + become the final component of the policy binding's resource + name. + + This value must start with a lowercase letter followed by up + to 62 lowercase letters, numbers, hyphens, or dots. Pattern, + /[a-z][a-z0-9-.]{2,62}/. + policy_binding (google.cloud.iam_v3beta.types.PolicyBinding): + Required. The policy binding to create. + validate_only (bool): + Optional. If set, validate the request and + preview the creation, but do not actually post + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + policy_binding_id: str = proto.Field( + proto.STRING, + number=2, + ) + policy_binding: policy_binding_resources.PolicyBinding = proto.Field( + proto.MESSAGE, + number=3, + message=policy_binding_resources.PolicyBinding, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetPolicyBindingRequest(proto.Message): + r"""Request message for GetPolicyBinding method. + + Attributes: + name (str): + Required. The name of the policy binding to retrieve. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePolicyBindingRequest(proto.Message): + r"""Request message for UpdatePolicyBinding method. + + Attributes: + policy_binding (google.cloud.iam_v3beta.types.PolicyBinding): + Required. The policy binding to update. + + The policy binding's ``name`` field is used to identify the + policy binding to update. + validate_only (bool): + Optional. If set, validate the request and + preview the update, but do not actually post it. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update + """ + + policy_binding: policy_binding_resources.PolicyBinding = proto.Field( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePolicyBindingRequest(proto.Message): + r"""Request message for DeletePolicyBinding method. + + Attributes: + name (str): + Required. The name of the policy binding to delete. + + Format: + + - ``projects/{project_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``projects/{project_number}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``folders/{folder_id}/locations/{location}/policyBindings/{policy_binding_id}`` + - ``organizations/{organization_id}/locations/{location}/policyBindings/{policy_binding_id}`` + etag (str): + Optional. The etag of the policy binding. + If this is provided, it must match the server's + etag. + validate_only (bool): + Optional. If set, validate the request and + preview the deletion, but do not actually post + it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListPolicyBindingsRequest(proto.Message): + r"""Request message for ListPolicyBindings method. + + Attributes: + parent (str): + Required. The parent resource, which owns the collection of + policy bindings. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + page_size (int): + Optional. The maximum number of policy + bindings to return. The service may return fewer + than this value. + + If unspecified, at most 50 policy bindings will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListPolicyBindings`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListPolicyBindings`` must match the call that provided the + page token. + filter (str): + Optional. An expression for filtering the results of the + request. Filter rules are case insensitive. Some eligible + fields for filtering are: + + - ``target`` + - ``policy`` + + Some examples of filter queries: + + - ``target:ex*``: The binding target's name starts with + "ex". + - ``target:example``: The binding target's name is + ``example``. + - ``policy:example``: The binding policy's name is + ``example``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPolicyBindingsResponse(proto.Message): + r"""Response message for ListPolicyBindings method. + + Attributes: + policy_bindings (MutableSequence[google.cloud.iam_v3beta.types.PolicyBinding]): + The policy bindings from the specified + parent. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + policy_bindings: MutableSequence[policy_binding_resources.PolicyBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchTargetPolicyBindingsRequest(proto.Message): + r"""Request message for SearchTargetPolicyBindings method. + + Attributes: + target (str): + Required. The target resource, which is bound to the policy + in the binding. + + Format: + + - ``//iam.googleapis.com/locations/global/workforcePools/POOL_ID`` + - ``//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID`` + - ``//iam.googleapis.com/locations/global/workspace/WORKSPACE_ID`` + - ``//cloudresourcemanager.googleapis.com/projects/{project_number}`` + - ``//cloudresourcemanager.googleapis.com/folders/{folder_id}`` + - ``//cloudresourcemanager.googleapis.com/organizations/{organization_id}`` + page_size (int): + Optional. The maximum number of policy + bindings to return. The service may return fewer + than this value. + + If unspecified, at most 50 policy bindings will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``SearchTargetPolicyBindingsRequest`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``SearchTargetPolicyBindingsRequest`` must match the call + that provided the page token. + parent (str): + Required. The parent resource where this search will be + performed. This should be the nearest Resource Manager + resource (project, folder, or organization) to the target. + + Format: + + - ``projects/{project_id}/locations/{location}`` + - ``projects/{project_number}/locations/{location}`` + - ``folders/{folder_id}/locations/{location}`` + - ``organizations/{organization_id}/locations/{location}`` + """ + + target: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=5, + ) + + +class SearchTargetPolicyBindingsResponse(proto.Message): + r"""Response message for SearchTargetPolicyBindings method. + + Attributes: + policy_bindings (MutableSequence[google.cloud.iam_v3beta.types.PolicyBinding]): + The policy bindings bound to the specified + target. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + policy_bindings: MutableSequence[policy_binding_resources.PolicyBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/principal_access_boundary_policies_service.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/principal_access_boundary_policies_service.py new file mode 100644 index 0000000000000000000000000000000000000000..0a429ce125eac57800ad6009dc2c7f62d36017a2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/principal_access_boundary_policies_service.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.iam_v3beta.types import ( + policy_binding_resources, + principal_access_boundary_policy_resources, +) + +__protobuf__ = proto.module( + package="google.iam.v3beta", + manifest={ + "CreatePrincipalAccessBoundaryPolicyRequest", + "GetPrincipalAccessBoundaryPolicyRequest", + "UpdatePrincipalAccessBoundaryPolicyRequest", + "DeletePrincipalAccessBoundaryPolicyRequest", + "ListPrincipalAccessBoundaryPoliciesRequest", + "ListPrincipalAccessBoundaryPoliciesResponse", + "SearchPrincipalAccessBoundaryPolicyBindingsRequest", + "SearchPrincipalAccessBoundaryPolicyBindingsResponse", + }, +) + + +class CreatePrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for + CreatePrincipalAccessBoundaryPolicyRequest method. + + Attributes: + parent (str): + Required. The parent resource where this principal access + boundary policy will be created. Only organizations are + supported. + + Format: + ``organizations/{organization_id}/locations/{location}`` + principal_access_boundary_policy_id (str): + Required. The ID to use for the principal access boundary + policy, which will become the final component of the + principal access boundary policy's resource name. + + This value must start with a lowercase letter followed by up + to 62 lowercase letters, numbers, hyphens, or dots. Pattern, + /[a-z][a-z0-9-.]{2,62}/. + principal_access_boundary_policy (google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy): + Required. The principal access boundary + policy to create. + validate_only (bool): + Optional. If set, validate the request and + preview the creation, but do not actually post + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + principal_access_boundary_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + principal_access_boundary_policy: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy = proto.Field( + proto.MESSAGE, + number=3, + message=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetPrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for GetPrincipalAccessBoundaryPolicy method. + + Attributes: + name (str): + Required. The name of the principal access boundary policy + to retrieve. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for UpdatePrincipalAccessBoundaryPolicy + method. + + Attributes: + principal_access_boundary_policy (google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy): + Required. The principal access boundary policy to update. + + The principal access boundary policy's ``name`` field is + used to identify the policy to update. + validate_only (bool): + Optional. If set, validate the request and + preview the update, but do not actually post it. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update + """ + + principal_access_boundary_policy: principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy = proto.Field( + proto.MESSAGE, + number=1, + message=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePrincipalAccessBoundaryPolicyRequest(proto.Message): + r"""Request message for DeletePrincipalAccessBoundaryPolicy + method. + + Attributes: + name (str): + Required. The name of the principal access boundary policy + to delete. + + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + etag (str): + Optional. The etag of the principal access + boundary policy. If this is provided, it must + match the server's etag. + validate_only (bool): + Optional. If set, validate the request and + preview the deletion, but do not actually post + it. + force (bool): + Optional. If set to true, the request will + force the deletion of the policy even if the + policy is referenced in policy bindings. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListPrincipalAccessBoundaryPoliciesRequest(proto.Message): + r"""Request message for ListPrincipalAccessBoundaryPolicies + method. + + Attributes: + parent (str): + Required. The parent resource, which owns the collection of + principal access boundary policies. + + Format: + ``organizations/{organization_id}/locations/{location}`` + page_size (int): + Optional. The maximum number of principal + access boundary policies to return. The service + may return fewer than this value. + + If unspecified, at most 50 principal access + boundary policies will be returned. The maximum + value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListPrincipalAccessBoundaryPolicies`` call. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListPrincipalAccessBoundaryPolicies`` must match the call + that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPrincipalAccessBoundaryPoliciesResponse(proto.Message): + r"""Response message for ListPrincipalAccessBoundaryPolicies + method. + + Attributes: + principal_access_boundary_policies (MutableSequence[google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicy]): + The principal access boundary policies from + the specified parent. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + principal_access_boundary_policies: MutableSequence[ + principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=principal_access_boundary_policy_resources.PrincipalAccessBoundaryPolicy, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchPrincipalAccessBoundaryPolicyBindingsRequest(proto.Message): + r"""Request message for + SearchPrincipalAccessBoundaryPolicyBindings rpc. + + Attributes: + name (str): + Required. The name of the principal access boundary policy. + Format: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{principal_access_boundary_policy_id}`` + page_size (int): + Optional. The maximum number of policy + bindings to return. The service may return fewer + than this value. + + If unspecified, at most 50 policy bindings will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``SearchPrincipalAccessBoundaryPolicyBindingsRequest`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``SearchPrincipalAccessBoundaryPolicyBindingsRequest`` must + match the call that provided the page token. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchPrincipalAccessBoundaryPolicyBindingsResponse(proto.Message): + r"""Response message for + SearchPrincipalAccessBoundaryPolicyBindings rpc. + + Attributes: + policy_bindings (MutableSequence[google.cloud.iam_v3beta.types.PolicyBinding]): + The policy bindings that reference the + specified policy. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + policy_bindings: MutableSequence[policy_binding_resources.PolicyBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policy_binding_resources.PolicyBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/principal_access_boundary_policy_resources.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/principal_access_boundary_policy_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..271256e78dc00b76576732227d1ff782275c2b3c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/iam_v3beta/types/principal_access_boundary_policy_resources.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.v3beta", + manifest={ + "PrincipalAccessBoundaryPolicy", + "PrincipalAccessBoundaryPolicyDetails", + "PrincipalAccessBoundaryPolicyRule", + }, +) + + +class PrincipalAccessBoundaryPolicy(proto.Message): + r"""An IAM principal access boundary policy resource. + + Attributes: + name (str): + Identifier. The resource name of the principal access + boundary policy. + + The following format is supported: + ``organizations/{organization_id}/locations/{location}/principalAccessBoundaryPolicies/{policy_id}`` + uid (str): + Output only. The globally unique ID of the + principal access boundary policy. + etag (str): + Optional. The etag for the principal access + boundary. If this is provided on update, it must + match the server's etag. + display_name (str): + Optional. The description of the principal + access boundary policy. Must be less than or + equal to 63 characters. + annotations (MutableMapping[str, str]): + Optional. User defined annotations. See + https://google.aip.dev/148#annotations for more + details such as format and size limitations + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the principal + access boundary policy was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the principal + access boundary policy was most recently + updated. + details (google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicyDetails): + Optional. The details for the principal + access boundary policy. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + details: "PrincipalAccessBoundaryPolicyDetails" = proto.Field( + proto.MESSAGE, + number=8, + message="PrincipalAccessBoundaryPolicyDetails", + ) + + +class PrincipalAccessBoundaryPolicyDetails(proto.Message): + r"""Principal access boundary policy details + + Attributes: + rules (MutableSequence[google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicyRule]): + Required. A list of principal access boundary + policy rules. The number of rules in a policy is + limited to 500. + enforcement_version (str): + Optional. The version number (for example, ``1`` or + ``latest``) that indicates which permissions are able to be + blocked by the policy. If empty, the PAB policy version will + be set to the most recent version number at the time of the + policy's creation. + """ + + rules: MutableSequence["PrincipalAccessBoundaryPolicyRule"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="PrincipalAccessBoundaryPolicyRule", + ) + enforcement_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class PrincipalAccessBoundaryPolicyRule(proto.Message): + r"""Principal access boundary policy rule that defines the + resource boundary. + + Attributes: + description (str): + Optional. The description of the principal + access boundary policy rule. Must be less than + or equal to 256 characters. + resources (MutableSequence[str]): + Required. A list of Resource Manager resources. If a + resource is listed in the rule, then the rule applies for + that resource and its descendants. The number of resources + in a policy is limited to 500 across all rules in the + policy. + + The following resource types are supported: + + - Organizations, such as + ``//cloudresourcemanager.googleapis.com/organizations/123``. + - Folders, such as + ``//cloudresourcemanager.googleapis.com/folders/123``. + - Projects, such as + ``//cloudresourcemanager.googleapis.com/projects/123`` or + ``//cloudresourcemanager.googleapis.com/projects/my-project-id``. + effect (google.cloud.iam_v3beta.types.PrincipalAccessBoundaryPolicyRule.Effect): + Required. The access relationship of + principals to the resources in this rule. + """ + + class Effect(proto.Enum): + r"""An effect to describe the access relationship. + + Values: + EFFECT_UNSPECIFIED (0): + Effect unspecified. + ALLOW (1): + Allows access to the resources in this rule. + """ + + EFFECT_UNSPECIFIED = 0 + ALLOW = 1 + + description: str = proto.Field( + proto.STRING, + number=1, + ) + resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + effect: Effect = proto.Field( + proto.ENUM, + number=3, + enum=Effect, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/__pycache__/locations_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/__pycache__/locations_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..106faccd8c879237b931f713510d97807bbeaffd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/__pycache__/locations_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations.proto new file mode 100644 index 0000000000000000000000000000000000000000..36a0b0e89ddcfdbf42a73239a006d804abbde341 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations.proto @@ -0,0 +1,108 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.cloud.location; + +import "google/api/annotations.proto"; +import "google/protobuf/any.proto"; +import "google/api/client.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/cloud/location;location"; +option java_multiple_files = true; +option java_outer_classname = "LocationsProto"; +option java_package = "com.google.cloud.location"; + +// An abstract interface that provides location-related information for +// a service. Service-specific metadata is provided through the +// [Location.metadata][google.cloud.location.Location.metadata] field. +service Locations { + option (google.api.default_host) = "cloud.googleapis.com"; + option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; + + // Lists information about the supported locations for this service. + rpc ListLocations(ListLocationsRequest) returns (ListLocationsResponse) { + option (google.api.http) = { + get: "/v1/{name=locations}" + additional_bindings { + get: "/v1/{name=projects/*}/locations" + } + }; + } + + // Gets information about a location. + rpc GetLocation(GetLocationRequest) returns (Location) { + option (google.api.http) = { + get: "/v1/{name=locations/*}" + additional_bindings { + get: "/v1/{name=projects/*/locations/*}" + } + }; + } +} + +// The request message for [Locations.ListLocations][google.cloud.location.Locations.ListLocations]. +message ListLocationsRequest { + // The resource that owns the locations collection, if applicable. + string name = 1; + + // The standard list filter. + string filter = 2; + + // The standard list page size. + int32 page_size = 3; + + // The standard list page token. + string page_token = 4; +} + +// The response message for [Locations.ListLocations][google.cloud.location.Locations.ListLocations]. +message ListLocationsResponse { + // A list of locations that matches the specified filter in the request. + repeated Location locations = 1; + + // The standard List next-page token. + string next_page_token = 2; +} + +// The request message for [Locations.GetLocation][google.cloud.location.Locations.GetLocation]. +message GetLocationRequest { + // Resource name for the location. + string name = 1; +} + +// A resource that represents Google Cloud Platform location. +message Location { + // Resource name for the location, which may vary between implementations. + // For example: `"projects/example-project/locations/us-east1"` + string name = 1; + + // The canonical id for this location. For example: `"us-east1"`. + string location_id = 4; + + // The friendly name for this location, typically a nearby city name. + // For example, "Tokyo". + string display_name = 5; + + // Cross-service attributes for the location. For example + // + // {"cloud.googleapis.com/region": "us-east1"} + map labels = 2; + + // Service-specific metadata. For example the available capacity at the given + // location. + google.protobuf.Any metadata = 3; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d77b5983617c193548311e3ac55588c8a311b69d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations_pb2.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/location/locations.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import client_pb2 as google_dot_api_dot_client__pb2 +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n%google/cloud/location/locations.proto\x12\x15google.cloud.location\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/protobuf/any.proto\x1a\x17google/api/client.proto"[\n\x14ListLocationsRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05\x12\x12\n\npage_token\x18\x04 \x01(\t"d\n\x15ListLocationsResponse\x12\x32\n\tlocations\x18\x01 \x03(\x0b\x32\x1f.google.cloud.location.Location\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t""\n\x12GetLocationRequest\x12\x0c\n\x04name\x18\x01 \x01(\t"\xd7\x01\n\x08Location\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0blocation_id\x18\x04 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x05 \x01(\t\x12;\n\x06labels\x18\x02 \x03(\x0b\x32+.google.cloud.location.Location.LabelsEntry\x12&\n\x08metadata\x18\x03 \x01(\x0b\x32\x14.google.protobuf.Any\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x32\xa4\x03\n\tLocations\x12\xab\x01\n\rListLocations\x12+.google.cloud.location.ListLocationsRequest\x1a,.google.cloud.location.ListLocationsResponse"?\x82\xd3\xe4\x93\x02\x39\x12\x14/v1/{name=locations}Z!\x12\x1f/v1/{name=projects/*}/locations\x12\x9e\x01\n\x0bGetLocation\x12).google.cloud.location.GetLocationRequest\x1a\x1f.google.cloud.location.Location"C\x82\xd3\xe4\x93\x02=\x12\x16/v1/{name=locations/*}Z#\x12!/v1/{name=projects/*/locations/*}\x1aH\xca\x41\x14\x63loud.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformBo\n\x19\x63om.google.cloud.locationB\x0eLocationsProtoP\x01Z=google.golang.org/genproto/googleapis/cloud/location;location\xf8\x01\x01\x62\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.cloud.location.locations_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\031com.google.cloud.locationB\016LocationsProtoP\001Z=google.golang.org/genproto/googleapis/cloud/location;location\370\001\001" + _globals["_LOCATION_LABELSENTRY"]._options = None + _globals["_LOCATION_LABELSENTRY"]._serialized_options = b"8\001" + _globals["_LOCATIONS"]._options = None + _globals[ + "_LOCATIONS" + ]._serialized_options = b"\312A\024cloud.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform" + _globals["_LOCATIONS"].methods_by_name["ListLocations"]._options = None + _globals["_LOCATIONS"].methods_by_name[ + "ListLocations" + ]._serialized_options = b"\202\323\344\223\0029\022\024/v1/{name=locations}Z!\022\037/v1/{name=projects/*}/locations" + _globals["_LOCATIONS"].methods_by_name["GetLocation"]._options = None + _globals["_LOCATIONS"].methods_by_name[ + "GetLocation" + ]._serialized_options = b"\202\323\344\223\002=\022\026/v1/{name=locations/*}Z#\022!/v1/{name=projects/*/locations/*}" + _globals["_LISTLOCATIONSREQUEST"]._serialized_start = 146 + _globals["_LISTLOCATIONSREQUEST"]._serialized_end = 237 + _globals["_LISTLOCATIONSRESPONSE"]._serialized_start = 239 + _globals["_LISTLOCATIONSRESPONSE"]._serialized_end = 339 + _globals["_GETLOCATIONREQUEST"]._serialized_start = 341 + _globals["_GETLOCATIONREQUEST"]._serialized_end = 375 + _globals["_LOCATION"]._serialized_start = 378 + _globals["_LOCATION"]._serialized_end = 593 + _globals["_LOCATION_LABELSENTRY"]._serialized_start = 548 + _globals["_LOCATION_LABELSENTRY"]._serialized_end = 593 + _globals["_LOCATIONS"]._serialized_start = 596 + _globals["_LOCATIONS"]._serialized_end = 1016 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9da2987cc7075177c3181600d218b9f5ac643b61 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/location/locations_pb2.pyi @@ -0,0 +1,95 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.api import annotations_pb2 as _annotations_pb2 +from google.api import client_pb2 as _client_pb2 +from google.protobuf import any_pb2 as _any_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class ListLocationsRequest(_message.Message): + __slots__ = ("name", "filter", "page_size", "page_token") + NAME_FIELD_NUMBER: _ClassVar[int] + FILTER_FIELD_NUMBER: _ClassVar[int] + PAGE_SIZE_FIELD_NUMBER: _ClassVar[int] + PAGE_TOKEN_FIELD_NUMBER: _ClassVar[int] + name: str + filter: str + page_size: int + page_token: str + def __init__( + self, + name: _Optional[str] = ..., + filter: _Optional[str] = ..., + page_size: _Optional[int] = ..., + page_token: _Optional[str] = ..., + ) -> None: ... + +class ListLocationsResponse(_message.Message): + __slots__ = ("locations", "next_page_token") + LOCATIONS_FIELD_NUMBER: _ClassVar[int] + NEXT_PAGE_TOKEN_FIELD_NUMBER: _ClassVar[int] + locations: _containers.RepeatedCompositeFieldContainer[Location] + next_page_token: str + def __init__( + self, + locations: _Optional[_Iterable[_Union[Location, _Mapping]]] = ..., + next_page_token: _Optional[str] = ..., + ) -> None: ... + +class GetLocationRequest(_message.Message): + __slots__ = ("name",) + NAME_FIELD_NUMBER: _ClassVar[int] + name: str + def __init__(self, name: _Optional[str] = ...) -> None: ... + +class Location(_message.Message): + __slots__ = ("name", "location_id", "display_name", "labels", "metadata") + class LabelsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + NAME_FIELD_NUMBER: _ClassVar[int] + LOCATION_ID_FIELD_NUMBER: _ClassVar[int] + DISPLAY_NAME_FIELD_NUMBER: _ClassVar[int] + LABELS_FIELD_NUMBER: _ClassVar[int] + METADATA_FIELD_NUMBER: _ClassVar[int] + name: str + location_id: str + display_name: str + labels: _containers.ScalarMap[str, str] + metadata: _any_pb2.Any + def __init__( + self, + name: _Optional[str] = ..., + location_id: _Optional[str] = ..., + display_name: _Optional[str] = ..., + labels: _Optional[_Mapping[str, str]] = ..., + metadata: _Optional[_Union[_any_pb2.Any, _Mapping]] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7af68203045ce7a265217fb8b66b00f7c23ed17c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/__init__.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.logging_v2 import ASCENDING, DESCENDING, __version__, handlers, types +from google.cloud.logging_v2.client import Client +from google.cloud.logging_v2.entries import ( + LogEntry, + ProtobufEntry, + StructEntry, + TextEntry, + logger_name_from_path, +) +from google.cloud.logging_v2.logger import Batch, Logger +from google.cloud.logging_v2.metric import Metric +from google.cloud.logging_v2.resource import Resource +from google.cloud.logging_v2.sink import Sink + +__all__ = ( + "__version__", + "ASCENDING", + "Batch", + "Client", + "DESCENDING", + "handlers", + "logger_name_from_path", + "Logger", + "LogEntry", + "Metric", + "ProtobufEntry", + "Resource", + "Sink", + "StructEntry", + "TextEntry", + "types", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..cce6648d3129e8a90eabc70badc862887e947379 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "3.15.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a003c45b6a33b421b4baa6f03d0ea11d77d77dc2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/__init__.py @@ -0,0 +1,33 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Python :mod:`logging` handlers for Google Cloud Logging.""" + +from google.cloud.logging_v2.handlers.app_engine import AppEngineHandler +from google.cloud.logging_v2.handlers.container_engine import ContainerEngineHandler +from google.cloud.logging_v2.handlers.handlers import ( + CloudLoggingFilter, + CloudLoggingHandler, + setup_logging, +) +from google.cloud.logging_v2.handlers.structured_log import StructuredLogHandler + +__all__ = [ + "AppEngineHandler", + "CloudLoggingFilter", + "CloudLoggingHandler", + "ContainerEngineHandler", + "StructuredLogHandler", + "setup_logging", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/middleware/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/middleware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bd32e4a901015d5642740efb69bf7a1aad30be9c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/middleware/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2017 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud.logging_v2.handlers.middleware.request import RequestMiddleware + +__all__ = ["RequestMiddleware"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1a45e3c5cddc1ef4ad40a42096b3749ddb2e4c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/handlers/transports/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Transport classes for Python logging integration. +Currently two options are provided, a synchronous transport that makes +an API call for each log statement, and an asynchronous handler that +sends the API using a :class:`~google.cloud.logging.logger.Batch` object in +the background. +""" + +from google.cloud.logging_v2.handlers.transports.background_thread import ( + BackgroundThreadTransport, +) +from google.cloud.logging_v2.handlers.transports.base import Transport +from google.cloud.logging_v2.handlers.transports.sync import SyncTransport + +__all__ = ["BackgroundThreadTransport", "SyncTransport", "Transport"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..6c7420d0d9cb016b1dfe8d5b1e260dfbd6f1d30e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-logging package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43d917cdb874a8bed1eebac1c782ad06d0ec3a28 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/__init__.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import absolute_import + +from google.cloud.logging_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + +from google.cloud.logging_v2 import handlers, types +from google.cloud.logging_v2.client import Client +from google.cloud.logging_v2.entries import ( + LogEntry, + ProtobufEntry, + StructEntry, + TextEntry, + logger_name_from_path, +) +from google.cloud.logging_v2.logger import Batch, Logger +from google.cloud.logging_v2.metric import Metric +from google.cloud.logging_v2.resource import Resource +from google.cloud.logging_v2.sink import Sink + +ASCENDING = "timestamp asc" +"""Query string to order by ascending timestamps.""" +DESCENDING = "timestamp desc" +"""Query string to order by descending timestamps.""" +_instrumentation_emitted = False +"""Flag for whether instrumentation info has been emitted""" + + +__all__ = ( + "__version__", + "ASCENDING", + "Batch", + "Client", + "DESCENDING", + "handlers", + "logger_name_from_path", + "Logger", + "LogEntry", + "Metric", + "ProtobufEntry", + "Resource", + "Sink", + "StructEntry", + "TextEntry", + "types", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_gapic.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_gapic.py new file mode 100644 index 0000000000000000000000000000000000000000..7e942e5033f3cd89a211e445d0182b116fe6e964 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_gapic.py @@ -0,0 +1,644 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Wrapper for adapting the autogenerated gapic client to the hand-written +client.""" + +from google.api_core import client_info, gapic_v1 +from google.protobuf.json_format import MessageToDict, ParseDict, ParseError + +from google.cloud.logging_v2._helpers import entry_from_resource +from google.cloud.logging_v2.metric import Metric +from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2Client +from google.cloud.logging_v2.services.logging_service_v2 import LoggingServiceV2Client +from google.cloud.logging_v2.services.metrics_service_v2 import MetricsServiceV2Client +from google.cloud.logging_v2.sink import Sink +from google.cloud.logging_v2.types import ( + CreateSinkRequest, + ListLogEntriesRequest, + ListLogMetricsRequest, + ListSinksRequest, + LogMetric, + LogSink, + UpdateSinkRequest, + WriteLogEntriesRequest, +) +from google.cloud.logging_v2.types import LogEntry as LogEntryPB + + +class _LoggingAPI(object): + """Helper mapping logging-related APIs.""" + + def __init__(self, gapic_api, client): + self._gapic_api = gapic_api + self._client = client + + def list_entries( + self, + resource_names, + *, + filter_=None, + order_by=None, + max_results=None, + page_size=None, + page_token=None, + ): + """Return a generator of log entry resources. + + Args: + resource_names (Sequence[str]): Names of one or more parent resources + from which to retrieve log entries: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + filter_ (str): a filter expression. See + https://cloud.google.com/logging/docs/view/advanced_filters + order_by (str) One of :data:`~logging_v2.ASCENDING` + or :data:`~logging_v2.DESCENDING`. + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + Returns: + Generator[~logging_v2.LogEntry] + """ + # full resource names are expected by the API + resource_names = resource_names + request = ListLogEntriesRequest( + resource_names=resource_names, + filter=filter_, + order_by=order_by, + page_size=page_size, + page_token=page_token, + ) + + response = self._gapic_api.list_log_entries(request=request) + log_iter = iter(response) + + # We attach a mutable loggers dictionary so that as Logger + # objects are created by entry_from_resource, they can be + # re-used by other log entries from the same logger. + loggers = {} + + if max_results is not None and max_results < 0: + raise ValueError("max_results must be positive") + + # create generator + def log_entries_pager(log_iter): + i = 0 + for entry in log_iter: + if max_results is not None and i >= max_results: + break + log_entry_dict = _parse_log_entry(LogEntryPB.pb(entry)) + yield entry_from_resource(log_entry_dict, self._client, loggers=loggers) + i += 1 + + return log_entries_pager(log_iter) + + def write_entries( + self, + entries, + *, + logger_name=None, + resource=None, + labels=None, + partial_success=True, + dry_run=False, + ): + """Log an entry resource via a POST request + + Args: + entries (Sequence[Mapping[str, ...]]): sequence of mappings representing + the log entry resources to log. + logger_name (Optional[str]): name of default logger to which to log the entries; + individual entries may override. + resource(Optional[Mapping[str, ...]]): default resource to associate with entries; + individual entries may override. + labels (Optional[Mapping[str, ...]]): default labels to associate with entries; + individual entries may override. + partial_success (Optional[bool]): Whether valid entries should be written even if + some other entries fail due to INVALID_ARGUMENT or + PERMISSION_DENIED errors. If any entry is not written, then + the response status is the error associated with one of the + failed entries and the response includes error details keyed + by the entries' zero-based index in the ``entries.write`` + method. + dry_run (Optional[bool]): + If true, the request should expect normal response, + but the entries won't be persisted nor exported. + Useful for checking whether the logging API endpoints are working + properly before sending valuable data. + """ + try: + log_entry_pbs = [_log_entry_mapping_to_pb(entry) for entry in entries] + except ParseError as e: + raise ValueError(f"Invalid log entry: {str(e)}") from e + + request = WriteLogEntriesRequest( + log_name=logger_name, + resource=resource, + labels=labels, + entries=log_entry_pbs, + partial_success=partial_success, + ) + self._gapic_api.write_log_entries(request=request) + + def logger_delete(self, logger_name): + """Delete all entries in a logger. + + Args: + logger_name (str): The resource name of the log to delete: + + :: + + "projects/[PROJECT_ID]/logs/[LOG_ID]" + "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + "folders/[FOLDER_ID]/logs/[LOG_ID]" + + ``[LOG_ID]`` must be URL-encoded. For example, + ``"projects/my-project-id/logs/syslog"``, + ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. + """ + self._gapic_api.delete_log(log_name=logger_name) + + +class _SinksAPI(object): + """Helper mapping sink-related APIs.""" + + def __init__(self, gapic_api, client): + self._gapic_api = gapic_api + self._client = client + + def list_sinks(self, parent, *, max_results=None, page_size=None, page_token=None): + """List sinks for the parent resource. + + Args: + parent (str): The parent resource whose sinks are to be listed: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[~logging_v2.Sink] + """ + request = ListSinksRequest( + parent=parent, page_size=page_size, page_token=page_token + ) + response = self._gapic_api.list_sinks(request) + sink_iter = iter(response) + + if max_results is not None and max_results < 0: + raise ValueError("max_results must be positive") + + def sinks_pager(sink_iter): + i = 0 + for entry in sink_iter: + if max_results is not None and i >= max_results: + break + # Convert the GAPIC sink type into the handwritten `Sink` type + yield Sink.from_api_repr(LogSink.to_dict(entry), client=self._client) + i += 1 + + return sinks_pager(sink_iter) + + def sink_create( + self, parent, sink_name, filter_, destination, *, unique_writer_identity=False + ): + """Create a sink resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create + + Args: + parent(str): The resource in which to create the sink, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + sink_name (str): The name of the sink. + filter_ (str): The advanced logs filter expression defining the + entries exported by the sink. + destination (str): Destination URI for the entries exported by + the sink. + unique_writer_identity (Optional[bool]): determines the kind of + IAM identity returned as writer_identity in the new sink. + + Returns: + dict: The sink resource returned from the API (converted from a + protobuf to a dictionary). + """ + sink_pb = LogSink(name=sink_name, filter=filter_, destination=destination) + request = CreateSinkRequest( + parent=parent, sink=sink_pb, unique_writer_identity=unique_writer_identity + ) + created_pb = self._gapic_api.create_sink(request=request) + return MessageToDict( + LogSink.pb(created_pb), + preserving_proto_field_name=False, + ) + + def sink_get(self, sink_name): + """Retrieve a sink resource. + + Args: + sink_name (str): The resource name of the sink, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + Returns: + dict: The sink object returned from the API (converted from a + protobuf to a dictionary). + """ + sink_pb = self._gapic_api.get_sink(sink_name=sink_name) + # NOTE: LogSink message type does not have an ``Any`` field + # so `MessageToDict`` can safely be used. + return MessageToDict( + LogSink.pb(sink_pb), + preserving_proto_field_name=False, + ) + + def sink_update( + self, + sink_name, + filter_, + destination, + *, + unique_writer_identity=False, + ): + """Update a sink resource. + + Args: + sink_name (str): Required. The resource name of the sink, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + filter_ (str): The advanced logs filter expression defining the + entries exported by the sink. + destination (str): destination URI for the entries exported by + the sink. + unique_writer_identity (Optional[bool]): determines the kind of + IAM identity returned as writer_identity in the new sink. + + + Returns: + dict: The sink resource returned from the API (converted from a + protobuf to a dictionary). + """ + name = sink_name.split("/")[-1] # parse name out of full resource name + sink_pb = LogSink( + name=name, + filter=filter_, + destination=destination, + ) + + request = UpdateSinkRequest( + sink_name=sink_name, + sink=sink_pb, + unique_writer_identity=unique_writer_identity, + ) + sink_pb = self._gapic_api.update_sink(request=request) + # NOTE: LogSink message type does not have an ``Any`` field + # so `MessageToDict`` can safely be used. + return MessageToDict( + LogSink.pb(sink_pb), + preserving_proto_field_name=False, + ) + + def sink_delete(self, sink_name): + """Delete a sink resource. + + Args: + sink_name (str): Required. The full resource name of the sink to delete, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + Example: ``"projects/my-project-id/sinks/my-sink-id"``. + """ + self._gapic_api.delete_sink(sink_name=sink_name) + + +class _MetricsAPI(object): + """Helper mapping sink-related APIs.""" + + def __init__(self, gapic_api, client): + self._gapic_api = gapic_api + self._client = client + + def list_metrics( + self, project, *, max_results=None, page_size=None, page_token=None + ): + """List metrics for the project associated with this client. + + Args: + project (str): ID of the project whose metrics are to be listed. + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[logging_v2.Metric] + """ + path = f"projects/{project}" + request = ListLogMetricsRequest( + parent=path, + page_size=page_size, + page_token=page_token, + ) + response = self._gapic_api.list_log_metrics(request=request) + metric_iter = iter(response) + + if max_results is not None and max_results < 0: + raise ValueError("max_results must be positive") + + def metrics_pager(metric_iter): + i = 0 + for entry in metric_iter: + if max_results is not None and i >= max_results: + break + # Convert GAPIC metrics type into handwritten `Metric` type + yield Metric.from_api_repr( + LogMetric.to_dict(entry), client=self._client + ) + i += 1 + + return metrics_pager(metric_iter) + + def metric_create(self, project, metric_name, filter_, description): + """Create a metric resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create + + Args: + project (str): ID of the project in which to create the metric. + metric_name (str): The name of the metric + filter_ (str): The advanced logs filter expression defining the + entries exported by the metric. + description (str): description of the metric. + """ + parent = f"projects/{project}" + metric_pb = LogMetric(name=metric_name, filter=filter_, description=description) + self._gapic_api.create_log_metric(parent=parent, metric=metric_pb) + + def metric_get(self, project, metric_name): + """Retrieve a metric resource. + + Args: + project (str): ID of the project containing the metric. + metric_name (str): The name of the metric + + Returns: + dict: The metric object returned from the API (converted from a + protobuf to a dictionary). + """ + path = f"projects/{project}/metrics/{metric_name}" + metric_pb = self._gapic_api.get_log_metric(metric_name=path) + # NOTE: LogMetric message type does not have an ``Any`` field + # so `MessageToDict`` can safely be used. + return MessageToDict( + LogMetric.pb(metric_pb), + preserving_proto_field_name=False, + ) + + def metric_update( + self, + project, + metric_name, + filter_, + description, + ): + """Update a metric resource. + + Args: + project (str): ID of the project containing the metric. + metric_name (str): the name of the metric + filter_ (str): the advanced logs filter expression defining the + entries exported by the metric. + description (str): description of the metric. + + Returns: + The metric object returned from the API (converted from a + protobuf to a dictionary). + """ + path = f"projects/{project}/metrics/{metric_name}" + metric_pb = LogMetric( + name=path, + filter=filter_, + description=description, + ) + metric_pb = self._gapic_api.update_log_metric( + metric_name=path, metric=metric_pb + ) + # NOTE: LogMetric message type does not have an ``Any`` field + # so `MessageToDict`` can safely be used. + return MessageToDict( + LogMetric.pb(metric_pb), + preserving_proto_field_name=False, + ) + + def metric_delete(self, project, metric_name): + """Delete a metric resource. + + Args: + project (str): ID of the project containing the metric. + metric_name (str): The name of the metric + """ + path = f"projects/{project}/metrics/{metric_name}" + self._gapic_api.delete_log_metric(metric_name=path) + + +def _parse_log_entry(entry_pb): + """Special helper to parse ``LogEntry`` protobuf into a dictionary. + + The ``proto_payload`` field in ``LogEntry`` is of type ``Any``. This + can be problematic if the type URL in the payload isn't in the + ``google.protobuf`` registry. To help with parsing unregistered types, + this function will remove ``proto_payload`` before parsing. + + Args: + entry_pb (LogEntry): Log entry protobuf. + + Returns: + dict: The parsed log entry. The ``protoPayload`` key may contain + the raw ``Any`` protobuf from ``entry_pb.proto_payload`` if + it could not be parsed. + """ + try: + return MessageToDict( + entry_pb, + preserving_proto_field_name=False, + ) + except TypeError: + if entry_pb.HasField("proto_payload"): + proto_payload = entry_pb.proto_payload + entry_pb.ClearField("proto_payload") + entry_mapping = MessageToDict( + entry_pb, + preserving_proto_field_name=False, + ) + entry_mapping["protoPayload"] = proto_payload + return entry_mapping + else: + raise + + +def _log_entry_mapping_to_pb(mapping): + """Helper for :meth:`write_entries`, et aliae + + Performs "impedance matching" between the protobuf attrs and + the keys expected in the JSON API. + """ + entry_pb = LogEntryPB.pb(LogEntryPB()) + # NOTE: We assume ``mapping`` was created in ``Batch.commit`` + # or ``Logger._make_entry_resource``. In either case, if + # the ``protoPayload`` key is present, we assume that the + # type URL is registered with ``google.protobuf`` and will + # not cause any issues in the JSON->protobuf conversion + # of the corresponding ``proto_payload`` in the log entry + # (it is an ``Any`` field). + ParseDict(mapping, entry_pb) + return LogEntryPB(entry_pb) + + +def _client_info_to_gapic(input_info): + """ + Helper function to convert api_core.client_info to + api_core.gapic_v1.client_info subclass + """ + return gapic_v1.client_info.ClientInfo( + python_version=input_info.python_version, + grpc_version=input_info.grpc_version, + api_core_version=input_info.api_core_version, + gapic_version=input_info.gapic_version, + client_library_version=input_info.client_library_version, + user_agent=input_info.user_agent, + rest_version=input_info.rest_version, + ) + + +def make_logging_api(client): + """Create an instance of the Logging API adapter. + + Args: + client (~logging_v2.client.Client): The client + that holds configuration details. + + Returns: + _LoggingAPI: A metrics API instance with the proper credentials. + """ + info = client._client_info + if isinstance(info, client_info.ClientInfo): + # convert into gapic-compatible subclass + info = _client_info_to_gapic(info) + + generated = LoggingServiceV2Client( + credentials=client._credentials, + client_info=info, + client_options=client._client_options, + ) + return _LoggingAPI(generated, client) + + +def make_metrics_api(client): + """Create an instance of the Metrics API adapter. + + Args: + client (~logging_v2.client.Client): The client + that holds configuration details. + + Returns: + _MetricsAPI: A metrics API instance with the proper credentials. + """ + info = client._client_info + if isinstance(info, client_info.ClientInfo): + # convert into gapic-compatible subclass + info = _client_info_to_gapic(info) + + generated = MetricsServiceV2Client( + credentials=client._credentials, + client_info=info, + client_options=client._client_options, + ) + return _MetricsAPI(generated, client) + + +def make_sinks_api(client): + """Create an instance of the Sinks API adapter. + + Args: + client (~logging_v2.client.Client): The client + that holds configuration details. + + Returns: + _SinksAPI: A metrics API instance with the proper credentials. + """ + info = client._client_info + if isinstance(info, client_info.ClientInfo): + # convert into gapic-compatible subclass + info = _client_info_to_gapic(info) + + generated = ConfigServiceV2Client( + credentials=client._credentials, + client_info=info, + client_options=client._client_options, + ) + return _SinksAPI(generated, client) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cbcc9c013b8b2b41f856b71cdbe79eec5ea178 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_helpers.py @@ -0,0 +1,151 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common logging helpers.""" + +import logging +from datetime import datetime, timedelta, timezone + +import requests + +from google.cloud.logging_v2.entries import ( + LogEntry, + ProtobufEntry, + StructEntry, + TextEntry, +) + +try: + from google.cloud.logging_v2.types import LogSeverity +except ImportError: # pragma: NO COVER + + class LogSeverity(object): + """Map severities for non-GAPIC usage.""" + + DEFAULT = 0 + DEBUG = 100 + INFO = 200 + NOTICE = 300 + WARNING = 400 + ERROR = 500 + CRITICAL = 600 + ALERT = 700 + EMERGENCY = 800 + + +_NORMALIZED_SEVERITIES = { + logging.CRITICAL: LogSeverity.CRITICAL, + logging.ERROR: LogSeverity.ERROR, + logging.WARNING: LogSeverity.WARNING, + logging.INFO: LogSeverity.INFO, + logging.DEBUG: LogSeverity.DEBUG, + logging.NOTSET: LogSeverity.DEFAULT, +} + +_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f%z" +"""Time format for timestamps used in API""" + +METADATA_URL = "http://metadata.google.internal./computeMetadata/v1/" +METADATA_HEADERS = {"Metadata-Flavor": "Google"} + + +def entry_from_resource(resource, client, loggers): + """Detect correct entry type from resource and instantiate. + + Args: + resource (dict): One entry resource from API response. + client (~logging_v2.client.Client): + Client that owns the log entry. + loggers (dict): + A mapping of logger fullnames -> loggers. If the logger + that owns the entry is not in ``loggers``, the entry + will have a newly-created logger. + + Returns: + google.cloud.logging_v2.entries._BaseEntry: + The entry instance, constructed via the resource + """ + if "textPayload" in resource: + return TextEntry.from_api_repr(resource, client, loggers=loggers) + + if "jsonPayload" in resource: + return StructEntry.from_api_repr(resource, client, loggers=loggers) + + if "protoPayload" in resource: + return ProtobufEntry.from_api_repr(resource, client, loggers=loggers) + + return LogEntry.from_api_repr(resource, client, loggers=loggers) + + +def retrieve_metadata_server(metadata_key, timeout=5): + """Retrieve the metadata key in the metadata server. + + See: https://cloud.google.com/compute/docs/storing-retrieving-metadata + + Args: + metadata_key (str): + Key of the metadata which will form the url. You can + also supply query parameters after the metadata key. + e.g. "tags?alt=json" + timeout (number): number of seconds to wait for the HTTP request + + Returns: + str: The value of the metadata key returned by the metadata server. + """ + url = METADATA_URL + metadata_key + + try: + response = requests.get(url, headers=METADATA_HEADERS, timeout=timeout) + + if response.status_code == requests.codes.ok: + return response.text + + except requests.exceptions.RequestException: + # Ignore the exception, connection failed means the attribute does not + # exist in the metadata server. + pass + + return None + + +def _normalize_severity(stdlib_level): + """Normalize a Python stdlib severity to LogSeverity enum. + + Args: + stdlib_level (int): 'levelno' from a :class:`logging.LogRecord` + + Returns: + int: Corresponding Stackdriver severity. + """ + return _NORMALIZED_SEVERITIES.get(stdlib_level, stdlib_level) + + +def _add_defaults_to_filter(filter_): + """Modify the input filter expression to add sensible defaults. + + Args: + filter_ (str): The original filter expression + + Returns: + str: sensible default filter string + """ + + # By default, requests should only return logs in the last 24 hours + yesterday = datetime.now(timezone.utc) - timedelta(days=1) + time_filter = f'timestamp>="{yesterday.strftime(_TIME_FORMAT)}"' + if filter_ is None: + filter_ = time_filter + elif "timestamp" not in filter_.lower(): + filter_ = f"{filter_} AND {time_filter}" + return filter_ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_http.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_http.py new file mode 100644 index 0000000000000000000000000000000000000000..50d62b8a81ee9a6ebfe2780f685f474362cbd93c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_http.py @@ -0,0 +1,549 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Interact with Cloud Logging via JSON-over-HTTP.""" + +import functools + +from google.api_core import page_iterator + +from google.cloud import _http +from google.cloud.logging_v2 import __version__ +from google.cloud.logging_v2._helpers import entry_from_resource +from google.cloud.logging_v2.metric import Metric +from google.cloud.logging_v2.sink import Sink + + +class Connection(_http.JSONConnection): + DEFAULT_API_ENDPOINT = "https://logging.googleapis.com" + + def __init__(self, client, *, client_info=None, api_endpoint=DEFAULT_API_ENDPOINT): + """A connection to Google Cloud Logging via the JSON REST API. + + Args: + client (google.cloud.logging_v2.cliet.Client): + The client that owns the current connection. + client_info (Optional[google.api_core.client_info.ClientInfo]): + Instance used to generate user agent. + client_options (Optional[google.api_core.client_options.ClientOptions]): + Client options used to set user options + on the client. API Endpoint should be set through client_options. + """ + super(Connection, self).__init__(client, client_info) + self.API_BASE_URL = api_endpoint + self._client_info.gapic_version = __version__ + self._client_info.client_library_version = __version__ + + API_VERSION = "v2" + """The version of the API, used in building the API call's URL.""" + + API_URL_TEMPLATE = "{api_base_url}/{api_version}{path}" + """A template for the URL of a particular API call.""" + + +class _LoggingAPI(object): + """Helper mapping logging-related APIs. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs + + :type client: :class:`~google.cloud.logging.client.Client` + :param client: The client used to make API requests. + """ + + def __init__(self, client): + self._client = client + self.api_request = client._connection.api_request + + def list_entries( + self, + resource_names, + *, + filter_=None, + order_by=None, + max_results=None, + page_size=None, + page_token=None, + ): + """Return a page of log entry resources. + + Args: + resource_names (Sequence[str]): Names of one or more parent resources + from which to retrieve log entries: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + filter_ (str): a filter expression. See + https://cloud.google.com/logging/docs/view/advanced_filters + order_by (str) One of :data:`~logging_v2.ASCENDING` + or :data:`~logging_v2.DESCENDING`. + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + Returns: + Generator[~logging_v2.LogEntry] + """ + extra_params = {"resourceNames": resource_names} + + if filter_ is not None: + extra_params["filter"] = filter_ + + if order_by is not None: + extra_params["orderBy"] = order_by + + if page_size is not None: + extra_params["pageSize"] = page_size + + path = "/entries:list" + # We attach a mutable loggers dictionary so that as Logger + # objects are created by entry_from_resource, they can be + # re-used by other log entries from the same logger. + loggers = {} + item_to_value = functools.partial(_item_to_entry, loggers=loggers) + iterator = page_iterator.HTTPIterator( + client=self._client, + api_request=self._client._connection.api_request, + path=path, + item_to_value=item_to_value, + items_key="entries", + page_token=page_token, + extra_params=extra_params, + ) + # This method uses POST to make a read-only request. + iterator._HTTP_METHOD = "POST" + + return _entries_pager(iterator, max_results) + + def write_entries( + self, + entries, + *, + logger_name=None, + resource=None, + labels=None, + partial_success=True, + dry_run=False, + ): + """Log an entry resource via a POST request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write + + Args: + entries (Sequence[Mapping[str, ...]]): sequence of mappings representing + the log entry resources to log. + logger_name (Optional[str]): name of default logger to which to log the entries; + individual entries may override. + resource(Optional[Mapping[str, ...]]): default resource to associate with entries; + individual entries may override. + labels (Optional[Mapping[str, ...]]): default labels to associate with entries; + individual entries may override. + partial_success (Optional[bool]): Whether valid entries should be written even if + some other entries fail due to INVALID_ARGUMENT or + PERMISSION_DENIED errors. If any entry is not written, then + the response status is the error associated with one of the + failed entries and the response includes error details keyed + by the entries' zero-based index in the ``entries.write`` + method. + dry_run (Optional[bool]): + If true, the request should expect normal response, + but the entries won't be persisted nor exported. + Useful for checking whether the logging API endpoints are working + properly before sending valuable data. + """ + data = { + "entries": list(entries), + "partialSuccess": partial_success, + "dry_run": dry_run, + } + + if logger_name is not None: + data["logName"] = logger_name + + if resource is not None: + data["resource"] = resource + + if labels is not None: + data["labels"] = labels + + self.api_request(method="POST", path="/entries:write", data=data) + + def logger_delete(self, logger_name): + """Delete all entries in a logger. + + Args: + logger_name (str): The resource name of the log to delete: + + :: + + "projects/[PROJECT_ID]/logs/[LOG_ID]" + "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + "folders/[FOLDER_ID]/logs/[LOG_ID]" + + ``[LOG_ID]`` must be URL-encoded. For example, + ``"projects/my-project-id/logs/syslog"``, + ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. + """ + path = f"/{logger_name}" + self.api_request(method="DELETE", path=path) + + +class _SinksAPI(object): + """Helper mapping sink-related APIs. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks + """ + + def __init__(self, client): + self._client = client + self.api_request = client._connection.api_request + + def list_sinks(self, parent, *, max_results=None, page_size=None, page_token=None): + """List sinks for the parent resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list + + Args: + parent (str): The parent resource whose sinks are to be listed: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[~logging_v2.Sink] + """ + extra_params = {} + + if page_size is not None: + extra_params["pageSize"] = page_size + + path = f"/{parent}/sinks" + iterator = page_iterator.HTTPIterator( + client=self._client, + api_request=self._client._connection.api_request, + path=path, + item_to_value=_item_to_sink, + items_key="sinks", + page_token=page_token, + extra_params=extra_params, + ) + + return _entries_pager(iterator, max_results) + + def sink_create( + self, parent, sink_name, filter_, destination, *, unique_writer_identity=False + ): + """Create a sink resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create + + Args: + parent(str): The resource in which to create the sink: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + sink_name (str): The name of the sink. + filter_ (str): The advanced logs filter expression defining the + entries exported by the sink. + destination (str): Destination URI for the entries exported by + the sink. + unique_writer_identity (Optional[bool]): determines the kind of + IAM identity returned as writer_identity in the new sink. + + Returns: + dict: The sink resource returned from the API. + """ + target = f"/{parent}/sinks" + data = {"name": sink_name, "filter": filter_, "destination": destination} + query_params = {"uniqueWriterIdentity": unique_writer_identity} + return self.api_request( + method="POST", path=target, data=data, query_params=query_params + ) + + def sink_get(self, sink_name): + """Retrieve a sink resource. + + Args: + sink_name (str): The resource name of the sink: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + Returns: + dict: The JSON sink object returned from the API. + """ + target = f"/{sink_name}" + return self.api_request(method="GET", path=target) + + def sink_update( + self, sink_name, filter_, destination, *, unique_writer_identity=False + ): + """Update a sink resource. + + Args: + sink_name (str): Required. The resource name of the sink: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + filter_ (str): The advanced logs filter expression defining the + entries exported by the sink. + destination (str): destination URI for the entries exported by + the sink. + unique_writer_identity (Optional[bool]): determines the kind of + IAM identity returned as writer_identity in the new sink. + + + Returns: + dict: The returned (updated) resource. + """ + target = f"/{sink_name}" + name = sink_name.split("/")[-1] # parse name out of full resource name + data = {"name": name, "filter": filter_, "destination": destination} + query_params = {"uniqueWriterIdentity": unique_writer_identity} + return self.api_request( + method="PUT", path=target, query_params=query_params, data=data + ) + + def sink_delete(self, sink_name): + """Delete a sink resource. + + Args: + sink_name (str): Required. The full resource name of the sink to delete, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + Example: ``"projects/my-project-id/sinks/my-sink-id"``. + """ + target = f"/{sink_name}" + self.api_request(method="DELETE", path=target) + + +class _MetricsAPI(object): + """Helper mapping sink-related APIs.""" + + def __init__(self, client): + self._client = client + self.api_request = client._connection.api_request + + def list_metrics( + self, project, *, max_results=None, page_size=None, page_token=None + ): + """List metrics for the project associated with this client. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list + + Args: + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[logging_v2.Metric] + + """ + extra_params = {} + + if page_size is not None: + extra_params["pageSize"] = page_size + + path = f"/projects/{project}/metrics" + iterator = page_iterator.HTTPIterator( + client=self._client, + api_request=self._client._connection.api_request, + path=path, + item_to_value=_item_to_metric, + items_key="metrics", + page_token=page_token, + extra_params=extra_params, + ) + return _entries_pager(iterator, max_results) + + def metric_create(self, project, metric_name, filter_, description): + """Create a metric resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create + + Args: + project (str): ID of the project in which to create the metric. + metric_name (str): The name of the metric + filter_ (str): The advanced logs filter expression defining the + entries exported by the metric. + description (str): description of the metric. + """ + target = f"/projects/{project}/metrics" + data = {"name": metric_name, "filter": filter_, "description": description} + self.api_request(method="POST", path=target, data=data) + + def metric_get(self, project, metric_name): + """Retrieve a metric resource. + + Args: + project (str): ID of the project containing the metric. + metric_name (str): The name of the metric + + Returns: + dict: The JSON metric object returned from the API. + """ + target = f"/projects/{project}/metrics/{metric_name}" + return self.api_request(method="GET", path=target) + + def metric_update(self, project, metric_name, filter_, description): + """Update a metric resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/update + + Args: + project (str): ID of the project containing the metric. + metric_name (str): the name of the metric + filter_ (str): the advanced logs filter expression defining the + entries exported by the metric. + description (str): description of the metric. + + Returns: + dict: The returned (updated) resource. + """ + target = f"/projects/{project}/metrics/{metric_name}" + data = {"name": metric_name, "filter": filter_, "description": description} + return self.api_request(method="PUT", path=target, data=data) + + def metric_delete(self, project, metric_name): + """Delete a metric resource. + + Args: + project (str): ID of the project containing the metric. + metric_name (str): The name of the metric + """ + target = f"/projects/{project}/metrics/{metric_name}" + self.api_request(method="DELETE", path=target) + + +def _entries_pager(page_iter, max_results=None): + if max_results is not None and max_results < 0: + raise ValueError("max_results must be positive") + + i = 0 + for page in page_iter: + if max_results is not None and i >= max_results: + break + yield page + i += 1 + + +def _item_to_entry(iterator, resource, loggers): + """Convert a log entry resource to the native object. + + .. note:: + + This method does not have the correct signature to be used as + the ``item_to_value`` argument to + :class:`~google.api_core.page_iterator.Iterator`. It is intended to be + patched with a mutable ``loggers`` argument that can be updated + on subsequent calls. For an example, see how the method is + used above in :meth:`_LoggingAPI.list_entries`. + + Args: + iterator (google.api_core.page_iterator.Iterator): The iterator that + is currently in use. + resource (dict): Log entry JSON resource returned from the API. + loggers (Mapping[str, logging_v2.logger.Logger]): + A mapping of logger fullnames -> loggers. If the logger + that owns the entry is not in ``loggers``, the entry + will have a newly-created logger. + + Returns: + ~logging_v2.entries._BaseEntry: The next log entry in the page. + """ + return entry_from_resource(resource, iterator.client, loggers) + + +def _item_to_sink(iterator, resource): + """Convert a sink resource to the native object. + + Args: + iterator (google.api_core.page_iterator.Iterator): The iterator that + is currently in use. + resource (dict): Sink JSON resource returned from the API. + + Returns: + ~logging_v2.sink.Sink: The next sink in the page. + """ + return Sink.from_api_repr(resource, iterator.client) + + +def _item_to_metric(iterator, resource): + """Convert a metric resource to the native object. + + Args: + iterator (google.api_core.page_iterator.Iterator): The iterator that + is currently in use. + resource (dict): Sink JSON resource returned from the API. + + Returns: + ~logging_v2.metric.Metric: + The next metric in the page. + """ + return Metric.from_api_repr(resource, iterator.client) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_instrumentation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_instrumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5a8426317551b243b48f67c0fa8740cc3990f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/_instrumentation.py @@ -0,0 +1,93 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Add diagnostic instrumentation source information to logs""" + +from google.cloud.logging_v2 import __version__ +from google.cloud.logging_v2.entries import StructEntry + +_DIAGNOSTIC_INFO_KEY = "logging.googleapis.com/diagnostic" +_INSTRUMENTATION_SOURCE_KEY = "instrumentation_source" +_PYTHON_LIBRARY_NAME = "python" + +_LIBRARY_VERSION = __version__ + +_MAX_NAME_LENGTH = 14 +_MAX_VERSION_LENGTH = 14 +_MAX_INSTRUMENTATION_ENTRIES = 3 + + +def _add_instrumentation(entries, **kw): + """Add instrumentation information to a list of entries + + A new diagnostic entry is prepended to the list of + entries. + + Args: + entries (Sequence[Mapping[str, ...]]): sequence of mappings representing + the log entry resources to log. + + Returns: + Sequence[Mapping[str, ...]]: entries with instrumentation info added to + the beginning of list. + """ + + diagnostic_entry = _create_diagnostic_entry(**kw) + entries.insert(0, diagnostic_entry.to_api_repr()) + return entries + + +def _create_diagnostic_entry(name=_PYTHON_LIBRARY_NAME, version=_LIBRARY_VERSION, **kw): + """Create a diagnostic log entry describing this library + + The diagnostic log consists of a list of library name and version objects + that have handled a given log entry. If this library is the originator + of the log entry, it will look like: + {logging.googleapis.com/diagnostic: {instrumentation_source: [{name: "python", version: "3.0.0"}]}} + + Args: + name(str): The name of this library (e.g. 'python') + version(str) The version of this library (e.g. '3.0.0') + + Returns: + google.cloud.logging_v2.LogEntry: Log entry with library information + """ + payload = { + _DIAGNOSTIC_INFO_KEY: { + _INSTRUMENTATION_SOURCE_KEY: [_get_instrumentation_source(name, version)] + } + } + # only keep the log_name and resource from the parent log + allow_list = ("log_name", "resource") + active_kws = {k: v for k, v in kw.items() if k in allow_list} + entry = StructEntry(payload=payload, **active_kws) + return entry + + +def _get_instrumentation_source(name=_PYTHON_LIBRARY_NAME, version=_LIBRARY_VERSION): + """Gets a JSON representation of the instrumentation_source + + Args: + name(str): The name of this library (e.g. 'python') + version(str) The version of this library (e.g. '3.0.0') + Returns: + obj: JSON object with library information + """ + source = {"name": name, "version": version} + # truncate strings to no more than _MAX_NAME_LENGTH characters + for key, val in source.items(): + source[key] = ( + val if len(val) <= _MAX_NAME_LENGTH else f"{val[:_MAX_NAME_LENGTH]}*" + ) + return source diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/client.py new file mode 100644 index 0000000000000000000000000000000000000000..7f0e62d58700bd758a8b271f5335fb579fda5afc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/client.py @@ -0,0 +1,428 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Client for interacting with the Google Cloud Logging API.""" + +import logging +import os +import sys + +import google.api_core.client_options +from google.cloud.client import ClientWithProject +from google.cloud.environment_vars import DISABLE_GRPC + +from google.cloud.logging_v2._helpers import _add_defaults_to_filter +from google.cloud.logging_v2._http import Connection +from google.cloud.logging_v2._http import _LoggingAPI as JSONLoggingAPI +from google.cloud.logging_v2._http import _MetricsAPI as JSONMetricsAPI +from google.cloud.logging_v2._http import _SinksAPI as JSONSinksAPI +from google.cloud.logging_v2.handlers import ( + CloudLoggingHandler, + StructuredLogHandler, + setup_logging, +) +from google.cloud.logging_v2.handlers._monitored_resources import detect_resource +from google.cloud.logging_v2.handlers.handlers import EXCLUDED_LOGGER_DEFAULTS +from google.cloud.logging_v2.logger import Logger +from google.cloud.logging_v2.metric import Metric +from google.cloud.logging_v2.resource import Resource +from google.cloud.logging_v2.sink import Sink + +_DISABLE_GRPC = os.getenv(DISABLE_GRPC, False) +_HAVE_GRPC = False + +try: + if not _DISABLE_GRPC: + # only import if DISABLE_GRPC is not set + from google.cloud.logging_v2 import _gapic + + _HAVE_GRPC = True +except ImportError: # pragma: NO COVER + # could not import gapic library. Fall back to HTTP mode + _HAVE_GRPC = False + _gapic = None + +_USE_GRPC = _HAVE_GRPC and not _DISABLE_GRPC + +_GAE_RESOURCE_TYPE = "gae_app" +_GKE_RESOURCE_TYPE = "k8s_container" +_GCF_RESOURCE_TYPE = "cloud_function" +_RUN_RESOURCE_TYPE = "cloud_run_revision" + + +class Client(ClientWithProject): + """Client to bundle configuration needed for API requests.""" + + _logging_api = None + _sinks_api = None + _metrics_api = None + + SCOPE = ( + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/cloud-platform", + ) + """The scopes required for authenticating as a Logging consumer.""" + + def __init__( + self, + *, + project=None, + credentials=None, + _http=None, + _use_grpc=None, + client_info=None, + client_options=None, + ): + """ + Args: + project (Optional[str]): the project which the client acts on behalf of. + If not passed, falls back to the default inferred + from the environment. + credentials (Optional[google.auth.credentials.Credentials]): + Thehe OAuth2 Credentials to use for this + client. If not passed (and if no ``_http`` object is + passed), falls back to the default inferred from the + environment. + _http (Optional[requests.Session]): HTTP object to make requests. + Can be any object that defines ``request()`` with the same interface as + :meth:`requests.Session.request`. If not passed, an + ``_http`` object is created that is bound to the + ``credentials`` for the current object. + This parameter should be considered private, and could + change in the future. + _use_grpc (Optional[bool]): Explicitly specifies whether + to use the gRPC transport or HTTP. If unset, + falls back to the ``GOOGLE_CLOUD_DISABLE_GRPC`` + environment variable + This parameter should be considered private, and could + change in the future. + client_info (Optional[Union[google.api_core.client_info.ClientInfo, google.api_core.gapic_v1.client_info.ClientInfo]]): + The client info used to send a user-agent string along with API + requests. If ``None``, then default info will be used. Generally, + you only need to set this if you're developing your own library + or partner tool. + client_options (Optional[Union[dict, google.api_core.client_options.ClientOptions]]): + Client options used to set user options + on the client. API Endpoint should be set through client_options. + """ + super(Client, self).__init__( + project=project, + credentials=credentials, + _http=_http, + client_options=client_options, + ) + + kw_args = {"client_info": client_info} + if client_options: + if isinstance(client_options, dict): + client_options = google.api_core.client_options.from_dict( + client_options + ) + if client_options.api_endpoint: + api_endpoint = client_options.api_endpoint + kw_args["api_endpoint"] = api_endpoint + + self._connection = Connection(self, **kw_args) + if client_info is None: + # if client info not passed in, use the discovered + # client info from _connection object + client_info = self._connection._client_info + + self._client_info = client_info + self._client_options = client_options + if _use_grpc is None: + self._use_grpc = _USE_GRPC + else: + self._use_grpc = _use_grpc + + self._handlers = set() + + @property + def logging_api(self): + """Helper for logging-related API calls. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs + """ + if self._logging_api is None: + if self._use_grpc: + self._logging_api = _gapic.make_logging_api(self) + else: + self._logging_api = JSONLoggingAPI(self) + return self._logging_api + + @property + def sinks_api(self): + """Helper for log sink-related API calls. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks + """ + if self._sinks_api is None: + if self._use_grpc: + self._sinks_api = _gapic.make_sinks_api(self) + else: + self._sinks_api = JSONSinksAPI(self) + return self._sinks_api + + @property + def metrics_api(self): + """Helper for log metric-related API calls. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics + """ + if self._metrics_api is None: + if self._use_grpc: + self._metrics_api = _gapic.make_metrics_api(self) + else: + self._metrics_api = JSONMetricsAPI(self) + return self._metrics_api + + def logger(self, name, *, labels=None, resource=None): + """Creates a logger bound to the current client. + + Args: + name (str): The name of the logger to be constructed. + resource (Optional[~logging_v2.Resource]): a monitored resource object + representing the resource the code was run on. If not given, will + be inferred from the environment. + labels (Optional[dict]): Mapping of default labels for entries written + via this logger. + + Returns: + ~logging_v2.logger.Logger: Logger created with the current client. + """ + return Logger(name, client=self, labels=labels, resource=resource) + + def list_entries( + self, + *, + resource_names=None, + filter_=None, + order_by=None, + max_results=None, + page_size=None, + page_token=None, + ): + """Return a generator of log entry resources. + + Args: + resource_names (Sequence[str]): Names of one or more parent resources + from which to retrieve log entries: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + If not passed, defaults to the project bound to the API's client. + + filter_ (str): a filter expression. See + https://cloud.google.com/logging/docs/view/advanced_filters + order_by (str) One of :data:`~logging_v2.ASCENDING` + or :data:`~logging_v2.DESCENDING`. + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[~logging_v2.LogEntry] + """ + if resource_names is None: + resource_names = [f"projects/{self.project}"] + filter_ = _add_defaults_to_filter(filter_) + + return self.logging_api.list_entries( + resource_names=resource_names, + filter_=filter_, + order_by=order_by, + max_results=max_results, + page_size=page_size, + page_token=page_token, + ) + + def sink(self, name, *, filter_=None, destination=None): + """Creates a sink bound to the current client. + + Args: + name (str): the name of the sink to be constructed. + filter_ (Optional[str]): the advanced logs filter expression + defining the entries exported by the sink. If not + passed, the instance should already exist, to be + refreshed via :meth:`Sink.reload`. + destination (str): destination URI for the entries exported by + the sink. If not passed, the instance should + already exist, to be refreshed via + :meth:`Sink.reload`. + + Returns: + ~logging_v2.sink.Sink: Sink created with the current client. + """ + return Sink(name, filter_=filter_, destination=destination, client=self) + + def list_sinks( + self, *, parent=None, max_results=None, page_size=None, page_token=None + ): + """List sinks for the a parent resource. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list + + Args: + parent (Optional[str]): The parent resource whose sinks are to be listed: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + + If not passed, defaults to the project bound to the API's client. + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[~logging_v2.Sink] + """ + if parent is None: + parent = f"projects/{self.project}" + return self.sinks_api.list_sinks( + parent=parent, + max_results=max_results, + page_size=page_size, + page_token=page_token, + ) + + def metric(self, name, *, filter_=None, description=""): + """Creates a metric bound to the current client. + + Args: + name (str): The name of the metric to be constructed. + filter_(Optional[str]): The advanced logs filter expression defining the + entries tracked by the metric. If not + passed, the instance should already exist, to be + refreshed via :meth:`Metric.reload`. + description (Optional[str]): The description of the metric to be constructed. + If not passed, the instance should already exist, + to be refreshed via :meth:`Metric.reload`. + + Returns: + ~logging_v2.metric.Metric: Metric created with the current client. + """ + return Metric(name, filter_=filter_, client=self, description=description) + + def list_metrics(self, *, max_results=None, page_size=None, page_token=None): + """List metrics for the project associated with this client. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list + + Args: + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + + Returns: + Generator[logging_v2.Metric] + """ + return self.metrics_api.list_metrics( + self.project, + max_results=max_results, + page_size=page_size, + page_token=page_token, + ) + + def get_default_handler(self, **kw): + """Return the default logging handler based on the local environment. + + Args: + kw (dict): keyword args passed to handler constructor + + Returns: + logging.Handler: The default log handler based on the environment + """ + monitored_resource = kw.pop("resource", detect_resource(self.project)) + + if isinstance(monitored_resource, Resource): + if monitored_resource.type == _GAE_RESOURCE_TYPE: + return CloudLoggingHandler(self, resource=monitored_resource, **kw) + elif monitored_resource.type == _GKE_RESOURCE_TYPE: + return StructuredLogHandler(**kw, project_id=self.project) + elif monitored_resource.type == _GCF_RESOURCE_TYPE: + # __stdout__ stream required to support structured logging on Python 3.7 + kw["stream"] = kw.get("stream", sys.__stdout__) + return StructuredLogHandler(**kw, project_id=self.project) + elif monitored_resource.type == _RUN_RESOURCE_TYPE: + return StructuredLogHandler(**kw, project_id=self.project) + return CloudLoggingHandler(self, resource=monitored_resource, **kw) + + def setup_logging( + self, *, log_level=logging.INFO, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, **kw + ): + """Attach default Cloud Logging handler to the root logger. + + This method uses the default log handler, obtained by + :meth:`~get_default_handler`, and attaches it to the root Python + logger, so that a call such as ``logging.warn``, as well as all child + loggers, will report to Cloud Logging. + + Args: + log_level (Optional[int]): The logging level threshold of the attached logger, + as set by the :meth:`logging.Logger.setLevel` method. Defaults to + :const:`logging.INFO`. + excluded_loggers (Optional[Tuple[str]]): The loggers to not attach the + handler to. This will always include the + loggers in the path of the logging client + itself. + Returns: + dict: keyword args passed to handler constructor + """ + handler = self.get_default_handler(**kw) + self._handlers.add(handler) + setup_logging(handler, log_level=log_level, excluded_loggers=excluded_loggers) + + def flush_handlers(self): + """Flushes all Python log handlers associated with this Client.""" + + for handler in self._handlers: + handler.flush() + + def close(self): + """Closes the Client and all handlers associated with this Client.""" + super(Client, self).close() + for handler in self._handlers: + handler.close() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/entries.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/entries.py new file mode 100644 index 0000000000000000000000000000000000000000..231687c86ca0a62f8a1bf8ff819dca3acebfb1ca --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/entries.py @@ -0,0 +1,359 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Log entries within the Google Cloud Logging API.""" + +import collections +import json +import re + +import google.cloud.appengine_logging # noqa: F401 + +# import officially supported proto definitions +import google.cloud.audit.audit_log_pb2 # noqa: F401 +from google.cloud._helpers import ( + _datetime_to_rfc3339, + _name_from_project_path, + _rfc3339_nanos_to_datetime, +) +from google.iam.v1.logging import audit_data_pb2 # noqa: F401 +from google.protobuf.json_format import MessageToDict, Parse +from google.protobuf.message import Message + +from google.cloud.logging_v2.resource import Resource + +_GLOBAL_RESOURCE = Resource(type="global", labels={}) + + +_LOGGER_TEMPLATE = re.compile( + r""" + projects/ # static prefix + (?P[^/]+) # initial letter, wordchars + hyphen + /logs/ # static midfix + (?P[^/]+) # initial letter, wordchars + allowed punc +""", + re.VERBOSE, +) + + +def logger_name_from_path(path, project=None): + """Validate a logger URI path and get the logger name. + + Args: + path (str): URI path for a logger API request + project (str): The project the path is expected to belong to + + Returns: + str: Logger name parsed from ``path``. + + Raises: + ValueError: If the ``path`` is ill-formed of if the project + from ``path`` does not agree with the ``project`` passed in. + """ + return _name_from_project_path(path, project, _LOGGER_TEMPLATE) + + +def _int_or_none(value): + """Helper: return an integer or ``None``.""" + if value is not None: + value = int(value) + return value + + +_LOG_ENTRY_FIELDS = ( # (name, default) + ("log_name", None), + ("labels", None), + ("insert_id", None), + ("severity", None), + ("http_request", None), + ("timestamp", None), + ("resource", _GLOBAL_RESOURCE), + ("trace", None), + ("span_id", None), + ("trace_sampled", None), + ("source_location", None), + ("operation", None), + ("logger", None), + ("payload", None), +) + + +_LogEntryTuple = collections.namedtuple( + "LogEntry", (field for field, _ in _LOG_ENTRY_FIELDS) +) + +_LogEntryTuple.__new__.__defaults__ = tuple(default for _, default in _LOG_ENTRY_FIELDS) + + +_LOG_ENTRY_PARAM_DOCSTRING = """\ + + Args: + log_name (str): The name of the logger used to post the entry. + labels (Optional[dict]): Mapping of labels for the entry + insert_id (Optional[str]): The ID used to identify an entry + uniquely. + severity (Optional[str]): The severity of the event being logged. + http_request (Optional[dict]): Info about HTTP request associated + with the entry. + timestamp (Optional[datetime.datetime]): Timestamp for the entry. + resource (Optional[google.cloud.logging_v2.resource.Resource]): + Monitored resource of the entry. + trace (Optional[str]): Trace ID to apply to the entry. + span_id (Optional[str]): Span ID within the trace for the log + entry. Specify the trace parameter if ``span_id`` is set. + trace_sampled (Optional[bool]): The sampling decision of the trace + associated with the log entry. + source_location (Optional[dict]): Location in source code from which + the entry was emitted. + operation (Optional[dict]): Additional information about a potentially + long-running operation associated with the log entry. + logger (logging_v2.logger.Logger): the logger used + to write the entry. +""" + +_LOG_ENTRY_SEE_ALSO_DOCSTRING = """\ + + See: + https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry +""" + + +class LogEntry(_LogEntryTuple): + __doc__ = ( + """ + Log entry. + + """ + + _LOG_ENTRY_PARAM_DOCSTRING + + _LOG_ENTRY_SEE_ALSO_DOCSTRING + ) + + received_timestamp = None + + @classmethod + def _extract_payload(cls, resource): + """Helper for :meth:`from_api_repr`""" + return None + + @classmethod + def from_api_repr(cls, resource, client, *, loggers=None): + """Construct an entry given its API representation + + Args: + resource (dict): text entry resource representation returned from + the API + client (~logging_v2.client.Client): + Client which holds credentials and project configuration. + loggers (Optional[dict]): + A mapping of logger fullnames -> loggers. If not + passed, the entry will have a newly-created logger if possible, + or an empty logger field if not. + + Returns: + google.cloud.logging.entries.LogEntry: Log entry parsed from ``resource``. + """ + if loggers is None: + loggers = {} + logger_fullname = resource["logName"] + logger = loggers.get(logger_fullname) + if logger is None: + # attempt to create a logger if possible + try: + logger_name = logger_name_from_path(logger_fullname, client.project) + logger = loggers[logger_fullname] = client.logger(logger_name) + except ValueError: + # log name is not scoped to a project. Leave logger as None + pass + payload = cls._extract_payload(resource) + insert_id = resource.get("insertId") + timestamp = resource.get("timestamp") + if timestamp is not None: + timestamp = _rfc3339_nanos_to_datetime(timestamp) + labels = resource.get("labels") + severity = resource.get("severity") + http_request = resource.get("httpRequest") + trace = resource.get("trace") + span_id = resource.get("spanId") + trace_sampled = resource.get("traceSampled") + source_location = resource.get("sourceLocation") + if source_location is not None: + line = source_location.pop("line", None) + source_location["line"] = _int_or_none(line) + operation = resource.get("operation") + + monitored_resource_dict = resource.get("resource") + monitored_resource = None + if monitored_resource_dict is not None: + monitored_resource = Resource._from_dict(monitored_resource_dict) + + inst = cls( + log_name=logger_fullname, + insert_id=insert_id, + timestamp=timestamp, + labels=labels, + severity=severity, + http_request=http_request, + resource=monitored_resource, + trace=trace, + span_id=span_id, + trace_sampled=trace_sampled, + source_location=source_location, + operation=operation, + logger=logger, + payload=payload, + ) + received = resource.get("receiveTimestamp") + if received is not None: + inst.received_timestamp = _rfc3339_nanos_to_datetime(received) + return inst + + def to_api_repr(self): + """API repr (JSON format) for entry.""" + info = {} + if self.log_name is not None: + info["logName"] = self.log_name + if self.resource is not None: + info["resource"] = self.resource._to_dict() + if self.labels is not None: + info["labels"] = self.labels + if self.insert_id is not None: + info["insertId"] = self.insert_id + if self.severity is not None: + if isinstance(self.severity, str): + info["severity"] = self.severity.upper() + else: + info["severity"] = self.severity + if self.http_request is not None: + info["httpRequest"] = self.http_request + if self.timestamp is not None: + info["timestamp"] = _datetime_to_rfc3339(self.timestamp) + if self.trace is not None: + info["trace"] = self.trace + if self.span_id is not None: + info["spanId"] = self.span_id + if self.trace_sampled is not None: + info["traceSampled"] = self.trace_sampled + if self.source_location is not None: + source_location = self.source_location.copy() + source_location["line"] = str(source_location.pop("line", 0)) + info["sourceLocation"] = source_location + if self.operation is not None: + info["operation"] = self.operation + return info + + +class TextEntry(LogEntry): + __doc__ = ( + """ + Log entry with text payload. + + """ + + _LOG_ENTRY_PARAM_DOCSTRING + + """ + + payload (str): payload for the log entry. + """ + + _LOG_ENTRY_SEE_ALSO_DOCSTRING + ) + + @classmethod + def _extract_payload(cls, resource): + """Helper for :meth:`from_api_repr`""" + return resource["textPayload"] + + def to_api_repr(self): + """API repr (JSON format) for entry.""" + info = super(TextEntry, self).to_api_repr() + info["textPayload"] = self.payload + return info + + +class StructEntry(LogEntry): + __doc__ = ( + """ + Log entry with JSON payload. + + """ + + _LOG_ENTRY_PARAM_DOCSTRING + + """ + + payload (dict): payload for the log entry. + """ + + _LOG_ENTRY_SEE_ALSO_DOCSTRING + ) + + @classmethod + def _extract_payload(cls, resource): + """Helper for :meth:`from_api_repr`""" + return resource["jsonPayload"] + + def to_api_repr(self): + """API repr (JSON format) for entry.""" + info = super(StructEntry, self).to_api_repr() + info["jsonPayload"] = self.payload + return info + + +class ProtobufEntry(LogEntry): + __doc__ = ( + """ + Log entry with protobuf message payload. + + """ + + _LOG_ENTRY_PARAM_DOCSTRING + + """ + + payload (google.protobuf.Message): payload for the log entry. + """ + + _LOG_ENTRY_SEE_ALSO_DOCSTRING + ) + + @classmethod + def _extract_payload(cls, resource): + """Helper for :meth:`from_api_repr`""" + return resource["protoPayload"] + + @property + def payload_pb(self): + if isinstance(self.payload, Message): + return self.payload + + @property + def payload_json(self): + if isinstance(self.payload, collections.abc.Mapping): + return self.payload + + def to_api_repr(self): + """API repr (JSON format) for entry.""" + info = super(ProtobufEntry, self).to_api_repr() + proto_payload = None + if self.payload_pb: + proto_payload = MessageToDict(self.payload) + elif self.payload_json: + proto_payload = dict(self.payload) + info["protoPayload"] = proto_payload + return info + + def parse_message(self, message): + """Parse payload into a protobuf message. + + Mutates the passed-in ``message`` in place. + + Args: + message (google.protobuf.Message): the message to be logged + """ + # NOTE: This assumes that ``payload`` is already a deserialized + # ``Any`` field and ``message`` has come from an imported + # ``pb2`` module with the relevant protobuf message type. + Parse(json.dumps(self.payload), message) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8d2b1297a0d756a420baa01c577fc21cc8f80a1a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/gapic_metadata.json @@ -0,0 +1,481 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.logging_v2", + "protoPackage": "google.logging.v2", + "schema": "1.0", + "services": { + "ConfigServiceV2": { + "clients": { + "grpc": { + "libraryClient": "ConfigServiceV2Client", + "rpcs": { + "CopyLogEntries": { + "methods": [ + "copy_log_entries" + ] + }, + "CreateBucket": { + "methods": [ + "create_bucket" + ] + }, + "CreateBucketAsync": { + "methods": [ + "create_bucket_async" + ] + }, + "CreateExclusion": { + "methods": [ + "create_exclusion" + ] + }, + "CreateLink": { + "methods": [ + "create_link" + ] + }, + "CreateSink": { + "methods": [ + "create_sink" + ] + }, + "CreateView": { + "methods": [ + "create_view" + ] + }, + "DeleteBucket": { + "methods": [ + "delete_bucket" + ] + }, + "DeleteExclusion": { + "methods": [ + "delete_exclusion" + ] + }, + "DeleteLink": { + "methods": [ + "delete_link" + ] + }, + "DeleteSink": { + "methods": [ + "delete_sink" + ] + }, + "DeleteView": { + "methods": [ + "delete_view" + ] + }, + "GetBucket": { + "methods": [ + "get_bucket" + ] + }, + "GetCmekSettings": { + "methods": [ + "get_cmek_settings" + ] + }, + "GetExclusion": { + "methods": [ + "get_exclusion" + ] + }, + "GetLink": { + "methods": [ + "get_link" + ] + }, + "GetSettings": { + "methods": [ + "get_settings" + ] + }, + "GetSink": { + "methods": [ + "get_sink" + ] + }, + "GetView": { + "methods": [ + "get_view" + ] + }, + "ListBuckets": { + "methods": [ + "list_buckets" + ] + }, + "ListExclusions": { + "methods": [ + "list_exclusions" + ] + }, + "ListLinks": { + "methods": [ + "list_links" + ] + }, + "ListSinks": { + "methods": [ + "list_sinks" + ] + }, + "ListViews": { + "methods": [ + "list_views" + ] + }, + "UndeleteBucket": { + "methods": [ + "undelete_bucket" + ] + }, + "UpdateBucket": { + "methods": [ + "update_bucket" + ] + }, + "UpdateBucketAsync": { + "methods": [ + "update_bucket_async" + ] + }, + "UpdateCmekSettings": { + "methods": [ + "update_cmek_settings" + ] + }, + "UpdateExclusion": { + "methods": [ + "update_exclusion" + ] + }, + "UpdateSettings": { + "methods": [ + "update_settings" + ] + }, + "UpdateSink": { + "methods": [ + "update_sink" + ] + }, + "UpdateView": { + "methods": [ + "update_view" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConfigServiceV2AsyncClient", + "rpcs": { + "CopyLogEntries": { + "methods": [ + "copy_log_entries" + ] + }, + "CreateBucket": { + "methods": [ + "create_bucket" + ] + }, + "CreateBucketAsync": { + "methods": [ + "create_bucket_async" + ] + }, + "CreateExclusion": { + "methods": [ + "create_exclusion" + ] + }, + "CreateLink": { + "methods": [ + "create_link" + ] + }, + "CreateSink": { + "methods": [ + "create_sink" + ] + }, + "CreateView": { + "methods": [ + "create_view" + ] + }, + "DeleteBucket": { + "methods": [ + "delete_bucket" + ] + }, + "DeleteExclusion": { + "methods": [ + "delete_exclusion" + ] + }, + "DeleteLink": { + "methods": [ + "delete_link" + ] + }, + "DeleteSink": { + "methods": [ + "delete_sink" + ] + }, + "DeleteView": { + "methods": [ + "delete_view" + ] + }, + "GetBucket": { + "methods": [ + "get_bucket" + ] + }, + "GetCmekSettings": { + "methods": [ + "get_cmek_settings" + ] + }, + "GetExclusion": { + "methods": [ + "get_exclusion" + ] + }, + "GetLink": { + "methods": [ + "get_link" + ] + }, + "GetSettings": { + "methods": [ + "get_settings" + ] + }, + "GetSink": { + "methods": [ + "get_sink" + ] + }, + "GetView": { + "methods": [ + "get_view" + ] + }, + "ListBuckets": { + "methods": [ + "list_buckets" + ] + }, + "ListExclusions": { + "methods": [ + "list_exclusions" + ] + }, + "ListLinks": { + "methods": [ + "list_links" + ] + }, + "ListSinks": { + "methods": [ + "list_sinks" + ] + }, + "ListViews": { + "methods": [ + "list_views" + ] + }, + "UndeleteBucket": { + "methods": [ + "undelete_bucket" + ] + }, + "UpdateBucket": { + "methods": [ + "update_bucket" + ] + }, + "UpdateBucketAsync": { + "methods": [ + "update_bucket_async" + ] + }, + "UpdateCmekSettings": { + "methods": [ + "update_cmek_settings" + ] + }, + "UpdateExclusion": { + "methods": [ + "update_exclusion" + ] + }, + "UpdateSettings": { + "methods": [ + "update_settings" + ] + }, + "UpdateSink": { + "methods": [ + "update_sink" + ] + }, + "UpdateView": { + "methods": [ + "update_view" + ] + } + } + } + } + }, + "LoggingServiceV2": { + "clients": { + "grpc": { + "libraryClient": "LoggingServiceV2Client", + "rpcs": { + "DeleteLog": { + "methods": [ + "delete_log" + ] + }, + "ListLogEntries": { + "methods": [ + "list_log_entries" + ] + }, + "ListLogs": { + "methods": [ + "list_logs" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "list_monitored_resource_descriptors" + ] + }, + "TailLogEntries": { + "methods": [ + "tail_log_entries" + ] + }, + "WriteLogEntries": { + "methods": [ + "write_log_entries" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LoggingServiceV2AsyncClient", + "rpcs": { + "DeleteLog": { + "methods": [ + "delete_log" + ] + }, + "ListLogEntries": { + "methods": [ + "list_log_entries" + ] + }, + "ListLogs": { + "methods": [ + "list_logs" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "list_monitored_resource_descriptors" + ] + }, + "TailLogEntries": { + "methods": [ + "tail_log_entries" + ] + }, + "WriteLogEntries": { + "methods": [ + "write_log_entries" + ] + } + } + } + } + }, + "MetricsServiceV2": { + "clients": { + "grpc": { + "libraryClient": "MetricsServiceV2Client", + "rpcs": { + "CreateLogMetric": { + "methods": [ + "create_log_metric" + ] + }, + "DeleteLogMetric": { + "methods": [ + "delete_log_metric" + ] + }, + "GetLogMetric": { + "methods": [ + "get_log_metric" + ] + }, + "ListLogMetrics": { + "methods": [ + "list_log_metrics" + ] + }, + "UpdateLogMetric": { + "methods": [ + "update_log_metric" + ] + } + } + }, + "grpc-async": { + "libraryClient": "MetricsServiceV2AsyncClient", + "rpcs": { + "CreateLogMetric": { + "methods": [ + "create_log_metric" + ] + }, + "DeleteLogMetric": { + "methods": [ + "delete_log_metric" + ] + }, + "GetLogMetric": { + "methods": [ + "get_log_metric" + ] + }, + "ListLogMetrics": { + "methods": [ + "list_log_metrics" + ] + }, + "UpdateLogMetric": { + "methods": [ + "update_log_metric" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..cce6648d3129e8a90eabc70badc862887e947379 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "3.15.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a003c45b6a33b421b4baa6f03d0ea11d77d77dc2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/__init__.py @@ -0,0 +1,33 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Python :mod:`logging` handlers for Google Cloud Logging.""" + +from google.cloud.logging_v2.handlers.app_engine import AppEngineHandler +from google.cloud.logging_v2.handlers.container_engine import ContainerEngineHandler +from google.cloud.logging_v2.handlers.handlers import ( + CloudLoggingFilter, + CloudLoggingHandler, + setup_logging, +) +from google.cloud.logging_v2.handlers.structured_log import StructuredLogHandler + +__all__ = [ + "AppEngineHandler", + "CloudLoggingFilter", + "CloudLoggingHandler", + "ContainerEngineHandler", + "StructuredLogHandler", + "setup_logging", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa8d854edfa0117207b1eea94010eb10b649d28 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/_helpers.py @@ -0,0 +1,283 @@ +# Copyright 2016 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helper functions for logging handlers.""" + +import json +import math +import re +import warnings + +try: + import flask +except ImportError: # pragma: NO COVER + flask = None + +import opentelemetry.trace + +from google.cloud.logging_v2.handlers.middleware.request import _get_django_request + +_DJANGO_CONTENT_LENGTH = "CONTENT_LENGTH" +_DJANGO_XCLOUD_TRACE_HEADER = "HTTP_X_CLOUD_TRACE_CONTEXT" +_DJANGO_TRACEPARENT = "HTTP_TRACEPARENT" +_DJANGO_USERAGENT_HEADER = "HTTP_USER_AGENT" +_DJANGO_REMOTE_ADDR_HEADER = "REMOTE_ADDR" +_DJANGO_REFERER_HEADER = "HTTP_REFERER" +_FLASK_XCLOUD_TRACE_HEADER = "X_CLOUD_TRACE_CONTEXT" +_FLASK_TRACEPARENT = "TRACEPARENT" +_PROTOCOL_HEADER = "SERVER_PROTOCOL" + + +def format_stackdriver_json(record, message): + """Helper to format a LogRecord in in Stackdriver fluentd format. + + Returns: + str: JSON str to be written to the log file. + + DEPRECATED: use StructuredLogHandler to write formatted logs to standard out instead. + """ + subsecond, second = math.modf(record.created) + + payload = { + "message": message, + "timestamp": {"seconds": int(second), "nanos": int(subsecond * 1e9)}, + "thread": record.thread, + "severity": record.levelname, + } + warnings.warn( + "format_stackdriver_json is deprecated. Use StructuredLogHandler instead.", + DeprecationWarning, + ) + return json.dumps(payload, ensure_ascii=False) + + +def get_request_data_from_flask(): + """Get http_request and trace data from flask request headers. + + Returns: + Tuple[Optional[dict], Optional[str], Optional[str], bool]: + Data related to the current http request, trace_id, span_id and trace_sampled + for the request. All fields will be None if a Flask request isn't found. + """ + if flask is None or not flask.request: + return None, None, None, False + + # build http_request + http_request = { + "requestMethod": flask.request.method, + "requestUrl": flask.request.url, + "userAgent": flask.request.user_agent.string, + "protocol": flask.request.environ.get(_PROTOCOL_HEADER), + } + + # find trace id and span id + # first check for w3c traceparent header + header = flask.request.headers.get(_FLASK_TRACEPARENT) + trace_id, span_id, trace_sampled = _parse_trace_parent(header) + if trace_id is None: + # traceparent not found. look for xcloud_trace_context header + header = flask.request.headers.get(_FLASK_XCLOUD_TRACE_HEADER) + trace_id, span_id, trace_sampled = _parse_xcloud_trace(header) + + return http_request, trace_id, span_id, trace_sampled + + +def get_request_data_from_django(): + """Get http_request and trace data from django request headers. + + Returns: + Tuple[Optional[dict], Optional[str], Optional[str], bool]: + Data related to the current http request, trace_id, span_id, and trace_sampled + for the request. All fields will be None if a django request isn't found. + """ + request = _get_django_request() + + if request is None: + return None, None, None, False + + # Django can raise django.core.exceptions.DisallowedHost here for a + # malformed HTTP_HOST header. But we don't want to import Django modules. + try: + request_url = request.build_absolute_uri() + except Exception: + request_url = None + + # build http_request + http_request = { + "requestMethod": request.method, + "requestUrl": request_url, + "userAgent": request.META.get(_DJANGO_USERAGENT_HEADER), + "protocol": request.META.get(_PROTOCOL_HEADER), + } + + # find trace id and span id + # first check for w3c traceparent header + header = request.META.get(_DJANGO_TRACEPARENT) + trace_id, span_id, trace_sampled = _parse_trace_parent(header) + if trace_id is None: + # traceparent not found. look for xcloud_trace_context header + header = request.META.get(_DJANGO_XCLOUD_TRACE_HEADER) + trace_id, span_id, trace_sampled = _parse_xcloud_trace(header) + + return http_request, trace_id, span_id, trace_sampled + + +def _parse_trace_parent(header): + """Given a w3 traceparent header, extract the trace and span ids. + For more information see https://www.w3.org/TR/trace-context/ + + Args: + header (str): the string extracted from the traceparent header + example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01 + Returns: + Tuple[Optional[dict], Optional[str], bool]: + The trace_id, span_id and trace_sampled extracted from the header + Each field will be None if header can't be parsed in expected format. + """ + trace_id = span_id = None + trace_sampled = False + # see https://www.w3.org/TR/trace-context/ for W3C traceparent format + if header: + try: + VERSION_PART = r"(?!ff)[a-f\d]{2}" + TRACE_ID_PART = r"(?![0]{32})[a-f\d]{32}" + PARENT_ID_PART = r"(?![0]{16})[a-f\d]{16}" + FLAGS_PART = r"[a-f\d]{2}" + regex = f"^\\s?({VERSION_PART})-({TRACE_ID_PART})-({PARENT_ID_PART})-({FLAGS_PART})(-.*)?\\s?$" + match = re.match(regex, header) + trace_id = match.group(2) + span_id = match.group(3) + # trace-flag component is an 8-bit bit field. Read as an int + int_flag = int(match.group(4), 16) + # trace sampled is set if the right-most bit in flag component is set + trace_sampled = bool(int_flag & 1) + except (IndexError, AttributeError): + # could not parse header as expected. Return None + pass + return trace_id, span_id, trace_sampled + + +def _parse_xcloud_trace(header): + """Given an X_CLOUD_TRACE header, extract the trace and span ids. + + Args: + header (str): the string extracted from the X_CLOUD_TRACE header + Returns: + Tuple[Optional[str], Optional[str], bool]: + The trace_id, span_id and trace_sampled extracted from the header + Each field will be None if not found. + """ + trace_id = span_id = None + trace_sampled = False + + # As per the format described at https://cloud.google.com/trace/docs/trace-context#legacy-http-header + # "X-Cloud-Trace-Context: TRACE_ID[/SPAN_ID][;o=OPTIONS]" + # for example: + # "X-Cloud-Trace-Context: 105445aa7843bc8bf206b12000100000/1;o=1" + # + # We expect: + # * trace_id (optional, 128-bit hex string): "105445aa7843bc8bf206b12000100000" + # * span_id (optional, 16-bit hex string): "0000000000000001" (needs to be converted into 16 bit hex string) + # * trace_sampled (optional, bool): true + if header: + try: + regex = r"([\w-]+)?(\/?([\w-]+))?(;?o=(\d))?" + match = re.match(regex, header) + trace_id = match.group(1) + span_id = match.group(3) + trace_sampled = match.group(5) == "1" + + # Convert the span ID to 16-bit hexadecimal instead of decimal + try: + span_id_int = int(span_id) + if span_id_int > 0 and span_id_int < 2**64: + span_id = f"{span_id_int:016x}" + else: + span_id = None + except (ValueError, TypeError): + span_id = None + + except IndexError: + pass + return trace_id, span_id, trace_sampled + + +def _retrieve_current_open_telemetry_span(): + """Helper to retrieve trace, span ID, and trace sampled information from the current + OpenTelemetry span. + + Returns: + Tuple[Optional[str], Optional[str], bool]: + Data related to the current trace_id, span_id, and trace_sampled for the + current OpenTelemetry span. If a span is not found, return None/False for all + fields. + """ + span = opentelemetry.trace.get_current_span() + if span != opentelemetry.trace.span.INVALID_SPAN: + context = span.get_span_context() + trace_id = opentelemetry.trace.format_trace_id(context.trace_id) + span_id = opentelemetry.trace.format_span_id(context.span_id) + trace_sampled = context.trace_flags.sampled + + return trace_id, span_id, trace_sampled + + return None, None, False + + +def get_request_data(): + """Helper to get http_request and trace data from supported web + frameworks (currently supported: Flask and Django), as well as OpenTelemetry. Attempts + to retrieve trace/spanID from OpenTelemetry first, before going to Traceparent then XCTC. + HTTP request data is taken from a supporting web framework (currently Flask or Django). + Because HTTP request data is decoupled from OpenTelemetry, it is possible to get as a + return value the HTTP request from the web framework of choice, and trace/span data from + OpenTelemetry, even if trace data is present in the HTTP request headers. + + Returns: + Tuple[Optional[dict], Optional[str], Optional[str], bool]: + Data related to the current http request, trace_id, span_id, and trace_sampled + for the request. All fields will be None if a http request isn't found. + """ + + ( + otel_trace_id, + otel_span_id, + otel_trace_sampled, + ) = _retrieve_current_open_telemetry_span() + + # Get HTTP request data + checkers = ( + get_request_data_from_django, + get_request_data_from_flask, + ) + + http_request, http_trace_id, http_span_id, http_trace_sampled = ( + None, + None, + None, + False, + ) + + for checker in checkers: + http_request, http_trace_id, http_span_id, http_trace_sampled = checker() + if http_request is None: + http_trace_id, http_span_id, http_trace_sampled = None, None, False + else: + break + + # otel_trace_id existing means the other return values are non-null + if otel_trace_id: + return http_request, otel_trace_id, otel_span_id, otel_trace_sampled + else: + return http_request, http_trace_id, http_span_id, http_trace_sampled diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/_monitored_resources.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/_monitored_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..f5035453914a57b5a200bdb1eca681d4104bc7fd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/_monitored_resources.py @@ -0,0 +1,303 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import logging +import os + +from google.cloud.logging_v2._helpers import retrieve_metadata_server +from google.cloud.logging_v2.resource import Resource + +_GAE_SERVICE_ENV = "GAE_SERVICE" +_GAE_VERSION_ENV = "GAE_VERSION" +_GAE_INSTANCE_ENV = "GAE_INSTANCE" +_GAE_ENV_VARS = [_GAE_SERVICE_ENV, _GAE_VERSION_ENV, _GAE_INSTANCE_ENV] +"""Environment variables set in App Engine environment.""" + +_CLOUD_RUN_SERVICE_ID = "K_SERVICE" +_CLOUD_RUN_REVISION_ID = "K_REVISION" +_CLOUD_RUN_CONFIGURATION_ID = "K_CONFIGURATION" +_CLOUD_RUN_SERVICE_ENV_VARS = [ + _CLOUD_RUN_SERVICE_ID, + _CLOUD_RUN_REVISION_ID, + _CLOUD_RUN_CONFIGURATION_ID, +] +_CLOUD_RUN_JOB_ID = "CLOUD_RUN_JOB" +_CLOUD_RUN_EXECUTION_ID = "CLOUD_RUN_EXECUTION" +_CLOUD_RUN_TASK_INDEX = "CLOUD_RUN_TASK_INDEX" +_CLOUD_RUN_TASK_ATTEMPT = "CLOUD_RUN_TASK_ATTEMPT" +_CLOUD_RUN_JOB_ENV_VARS = [ + _CLOUD_RUN_JOB_ID, + _CLOUD_RUN_EXECUTION_ID, + _CLOUD_RUN_TASK_INDEX, + _CLOUD_RUN_TASK_ATTEMPT, +] +"""Environment variables set in Cloud Run environment.""" + +_FUNCTION_TARGET = "FUNCTION_TARGET" +_FUNCTION_SIGNATURE = "FUNCTION_SIGNATURE_TYPE" +_FUNCTION_NAME = "FUNCTION_NAME" +_FUNCTION_REGION = "FUNCTION_REGION" +_FUNCTION_ENTRY = "ENTRY_POINT" +_FUNCTION_ENV_VARS = [_FUNCTION_TARGET, _FUNCTION_SIGNATURE, _CLOUD_RUN_SERVICE_ID] +_LEGACY_FUNCTION_ENV_VARS = [_FUNCTION_NAME, _FUNCTION_REGION, _FUNCTION_ENTRY] +"""Environment variables set in Cloud Functions environments.""" + + +_REGION_ID = "instance/region" +_ZONE_ID = "instance/zone" +_GCE_INSTANCE_ID = "instance/id" +"""Attribute in metadata server for compute region and instance.""" + +_GKE_CLUSTER_NAME = "instance/attributes/cluster-name" +"""Attribute in metadata server when in GKE environment.""" + +_GKE_CLUSTER_LOCATION = "instance/attributes/cluster-location" +"""Attribute in metadata server when in GKE environment.""" + +_PROJECT_NAME = "project/project-id" +"""Attribute in metadata server when in GKE environment.""" + +_GAE_RESOURCE_TYPE = "gae_app" +"""Resource type for App Engine environment.""" + +_CLOUD_RUN_JOB_RESOURCE_TYPE = "cloud_run_job" +"""Resource type for Cloud Run Jobs.""" + +_GAE_TRACE_ID_LABEL = "appengine.googleapis.com/trace_id" +"""Extra trace label to be added on App Engine environments""" + +_CLOUD_RUN_JOBS_EXECUTION_NAME_LABEL = "run.googleapis.com/execution_name" +_CLOUD_RUN_JOBS_TASK_INDEX_LABEL = "run.googleapis.com/task_index" +_CLOUD_RUN_JOBS_TASK_ATTEMPT_LABEL = "run.googleapis.com/task_attempt" +"""Extra labels for Cloud Run environments to be recognized by Cloud Run Jobs web UI.""" + + +def _create_functions_resource(): + """Create a standardized Cloud Functions resource. + Returns: + google.cloud.logging.Resource + """ + project = retrieve_metadata_server(_PROJECT_NAME) + region = retrieve_metadata_server(_REGION_ID) + if _FUNCTION_NAME in os.environ: + function_name = os.environ.get(_FUNCTION_NAME) + elif _CLOUD_RUN_SERVICE_ID in os.environ: + function_name = os.environ.get(_CLOUD_RUN_SERVICE_ID) + else: + function_name = "" + resource = Resource( + type="cloud_function", + labels={ + "project_id": project if project else "", + "function_name": function_name if function_name else "", + "region": region.split("/")[-1] if region else "", + }, + ) + return resource + + +def _create_kubernetes_resource(): + """Create a standardized Kubernetes resource. + Returns: + google.cloud.logging.Resource + """ + location = retrieve_metadata_server(_GKE_CLUSTER_LOCATION) + cluster_name = retrieve_metadata_server(_GKE_CLUSTER_NAME) + project = retrieve_metadata_server(_PROJECT_NAME) + + resource = Resource( + type="k8s_container", + labels={ + "project_id": project if project else "", + "location": location if location else "", + "cluster_name": cluster_name if cluster_name else "", + }, + ) + return resource + + +def _create_compute_resource(): + """Create a standardized Compute Engine resource. + Returns: + google.cloud.logging.Resource + """ + instance = retrieve_metadata_server(_GCE_INSTANCE_ID) + zone = retrieve_metadata_server(_ZONE_ID) + project = retrieve_metadata_server(_PROJECT_NAME) + resource = Resource( + type="gce_instance", + labels={ + "project_id": project if project else "", + "instance_id": instance if instance else "", + "zone": zone if zone else "", + }, + ) + return resource + + +def _create_cloud_run_service_resource(): + """Create a standardized Cloud Run service resource. + Returns: + google.cloud.logging.Resource + """ + region = retrieve_metadata_server(_REGION_ID) + project = retrieve_metadata_server(_PROJECT_NAME) + resource = Resource( + type="cloud_run_revision", + labels={ + "project_id": project if project else "", + "service_name": os.environ.get(_CLOUD_RUN_SERVICE_ID, ""), + "revision_name": os.environ.get(_CLOUD_RUN_REVISION_ID, ""), + "location": region.split("/")[-1] if region else "", + "configuration_name": os.environ.get(_CLOUD_RUN_CONFIGURATION_ID, ""), + }, + ) + return resource + + +def _create_cloud_run_job_resource(): + """Create a standardized Cloud Run job resource. + Returns: + google.cloud.logging.Resource + """ + region = retrieve_metadata_server(_REGION_ID) + project = retrieve_metadata_server(_PROJECT_NAME) + resource = Resource( + type=_CLOUD_RUN_JOB_RESOURCE_TYPE, + labels={ + "project_id": project if project else "", + "job_name": os.environ.get(_CLOUD_RUN_JOB_ID, ""), + "location": region.split("/")[-1] if region else "", + }, + ) + return resource + + +def _create_app_engine_resource(): + """Create a standardized App Engine resource. + Returns: + google.cloud.logging.Resource + """ + zone = retrieve_metadata_server(_ZONE_ID) + project = retrieve_metadata_server(_PROJECT_NAME) + resource = Resource( + type=_GAE_RESOURCE_TYPE, + labels={ + "project_id": project if project else "", + "module_id": os.environ.get(_GAE_SERVICE_ENV, ""), + "version_id": os.environ.get(_GAE_VERSION_ENV, ""), + "zone": zone if zone else "", + }, + ) + return resource + + +def _create_global_resource(project): + """Create a global resource. + Args: + project (str): The project ID to pass on to the resource + Returns: + google.cloud.logging.Resource + """ + return Resource(type="global", labels={"project_id": project if project else ""}) + + +def detect_resource(project=""): + """Return the default monitored resource based on the local environment. + If GCP resource not found, defaults to `global`. + + Args: + project (str): The project ID to pass on to the resource (if needed) + Returns: + google.cloud.logging.Resource: The default resource based on the environment + """ + gke_cluster_name = retrieve_metadata_server(_GKE_CLUSTER_NAME) + gce_instance_name = retrieve_metadata_server(_GCE_INSTANCE_ID) + + if all([env in os.environ for env in _GAE_ENV_VARS]): + # App Engine Flex or Standard + return _create_app_engine_resource() + elif gke_cluster_name is not None: + # Kubernetes Engine + return _create_kubernetes_resource() + elif all([env in os.environ for env in _LEGACY_FUNCTION_ENV_VARS]) or all( + [env in os.environ for env in _FUNCTION_ENV_VARS] + ): + # Cloud Functions + return _create_functions_resource() + elif all([env in os.environ for env in _CLOUD_RUN_SERVICE_ENV_VARS]): + # Cloud Run + return _create_cloud_run_service_resource() + elif all([env in os.environ for env in _CLOUD_RUN_JOB_ENV_VARS]): + # Cloud Run + return _create_cloud_run_job_resource() + elif gce_instance_name is not None: + # Compute Engine + return _create_compute_resource() + else: + # use generic global resource + return _create_global_resource(project) + + +@functools.lru_cache(maxsize=None) +def _get_environmental_labels(resource_type): + """Builds a dictionary of labels to be inserted into a LogRecord of the given resource type. + This function should only build a dict of items that are consistent across multiple logging statements + of the same resource type, such as environment variables. Th + + Returns: + dict: + A dict representation of labels and the values of those labels + """ + labels = {} + environ_vars = { + _CLOUD_RUN_JOB_RESOURCE_TYPE: { + _CLOUD_RUN_JOBS_EXECUTION_NAME_LABEL: _CLOUD_RUN_EXECUTION_ID, + _CLOUD_RUN_JOBS_TASK_INDEX_LABEL: _CLOUD_RUN_TASK_INDEX, + _CLOUD_RUN_JOBS_TASK_ATTEMPT_LABEL: _CLOUD_RUN_TASK_ATTEMPT, + } + } + + if resource_type in environ_vars: + for key, env_var in environ_vars[resource_type].items(): + val = os.environ.get(env_var, "") + if val: + labels[key] = val + + return labels + + +def add_resource_labels(resource: Resource, record: logging.LogRecord): + """Returns additional labels to be appended on to a LogRecord object based on the + local environment. Defaults to an empty dictionary if none apply. This is only to be + used for CloudLoggingHandler, as the structured logging daemon already does this. + + Args: + resource (google.cloud.logging.Resource): Resource based on the environment + record (logging.LogRecord): A LogRecord object representing a log record + Returns: + Dict[str, str]: New labels to append to the labels of the LogRecord + """ + if not resource: + return None + + # Get environmental labels from the resource type + labels = _get_environmental_labels(resource.type) + + # Add labels from log record + if resource.type == _GAE_RESOURCE_TYPE and record._trace is not None: + labels[_GAE_TRACE_ID_LABEL] = record._trace + + return labels diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/app_engine.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/app_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..a65d16a0e655f542c1197af25e707751e3ad345a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/app_engine.py @@ -0,0 +1,139 @@ +# Copyright 2016 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Logging handler for App Engine Flexible + +Sends logs to the Cloud Logging API with the appropriate resource +and labels for App Engine logs. +""" + +import logging +import os +import warnings + +from google.cloud.logging_v2.handlers._helpers import get_request_data +from google.cloud.logging_v2.handlers._monitored_resources import ( + _create_app_engine_resource, +) +from google.cloud.logging_v2.handlers.transports import BackgroundThreadTransport + +_DEFAULT_GAE_LOGGER_NAME = "app" + +_GAE_PROJECT_ENV_FLEX = "GCLOUD_PROJECT" +_GAE_PROJECT_ENV_STANDARD = "GOOGLE_CLOUD_PROJECT" +_GAE_SERVICE_ENV = "GAE_SERVICE" +_GAE_VERSION_ENV = "GAE_VERSION" + +_TRACE_ID_LABEL = "appengine.googleapis.com/trace_id" + +_DEPRECATION_MSG = "AppEngineHandler is deprecated. Use CloudLoggingHandler instead." + + +class AppEngineHandler(logging.StreamHandler): + """A logging handler that sends App Engine-formatted logs to Stackdriver. + + DEPRECATED: use CloudLoggingHandler instead. + """ + + def __init__( + self, + client, + *, + name=_DEFAULT_GAE_LOGGER_NAME, + transport=BackgroundThreadTransport, + stream=None, + ): + """ + Args: + client (~logging_v2.client.Client): The authenticated + Google Cloud Logging client for this handler to use. + name (Optional[str]): Name for the logger. + transport (Optional[~logging_v2.transports.Transport]): + The transport class. It should be a subclass + of :class:`.Transport`. If unspecified, + :class:`.BackgroundThreadTransport` will be used. + stream (Optional[IO]): Stream to be used by the handler. + + """ + super(AppEngineHandler, self).__init__(stream) + self.name = name + self.client = client + self.transport = transport(client, name) + self.project_id = os.environ.get( + _GAE_PROJECT_ENV_FLEX, os.environ.get(_GAE_PROJECT_ENV_STANDARD, "") + ) + self.module_id = os.environ.get(_GAE_SERVICE_ENV, "") + self.version_id = os.environ.get(_GAE_VERSION_ENV, "") + self.resource = self.get_gae_resource() + + warnings.warn(_DEPRECATION_MSG, DeprecationWarning) + + def get_gae_resource(self): + """Return the GAE resource using the environment variables. + + Returns: + google.cloud.logging_v2.resource.Resource: Monitored resource for GAE. + """ + return _create_app_engine_resource() + + def get_gae_labels(self): + """Return the labels for GAE app. + + If the trace ID can be detected, it will be included as a label. + Currently, no other labels are included. + + Returns: + dict: Labels for GAE app. + """ + gae_labels = {} + + _, trace_id, _, _ = get_request_data() + if trace_id is not None: + gae_labels[_TRACE_ID_LABEL] = trace_id + + return gae_labels + + def emit(self, record): + """Actually log the specified logging record. + + Overrides the default emit behavior of ``StreamHandler``. + + See https://docs.python.org/2/library/logging.html#handler-objects + + Args: + record (logging.LogRecord): The record to be logged. + """ + message = super(AppEngineHandler, self).format(record) + inferred_http, inferred_trace, _, _ = get_request_data() + if inferred_trace is not None: + inferred_trace = f"projects/{self.project_id}/traces/{inferred_trace}" + # allow user overrides + trace = getattr(record, "trace", inferred_trace) + span_id = getattr(record, "span_id", None) + http_request = getattr(record, "http_request", inferred_http) + resource = getattr(record, "resource", self.resource) + user_labels = getattr(record, "labels", {}) + # merge labels + gae_labels = self.get_gae_labels() + gae_labels.update(user_labels) + # send off request + self.transport.send( + record, + message, + resource=resource, + labels=gae_labels, + trace=trace, + span_id=span_id, + http_request=http_request, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/container_engine.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/container_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..3842111b47d4c51e629c79ebdf00c2c3e10ea49d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/container_engine.py @@ -0,0 +1,62 @@ +# Copyright 2016 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Logging handler for Google Container Engine (GKE). + +Formats log messages in a JSON format, so that Kubernetes clusters with the +fluentd Google Cloud plugin installed can format their log messages so that +metadata such as log level is properly captured. +""" + +import logging.handlers +import warnings + +from google.cloud.logging_v2.handlers._helpers import format_stackdriver_json + +_DEPRECATION_MSG = ( + "ContainerEngineHandler is deprecated. Use StructuredLogHandler instead." +) + + +class ContainerEngineHandler(logging.StreamHandler): + """Handler to format log messages the format expected by GKE fluent. + + This handler is written to format messages for the Google Container Engine + (GKE) fluentd plugin, so that metadata such as log level are properly set. + + DEPRECATED: use StructuredLogHandler to write formatted logs to standard out instead. + """ + + def __init__(self, *, name=None, stream=None): + """ + Args: + name (Optional[str]): The name of the custom log in Cloud Logging. + stream (Optional[IO]): Stream to be used by the handler. + + """ + super(ContainerEngineHandler, self).__init__(stream=stream) + self.name = name + warnings.warn(_DEPRECATION_MSG, DeprecationWarning) + + def format(self, record): + """Format the message into JSON expected by fluentd. + + Args: + record (logging.LogRecord): The log record. + + Returns: + str: A JSON string formatted for GKE fluentd. + """ + message = super(ContainerEngineHandler, self).format(record) + return format_stackdriver_json(record, message) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/handlers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab7d1e3f0c77612eefc87cdf4317eedc373984 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/handlers.py @@ -0,0 +1,338 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Python :mod:`logging` handlers for Cloud Logging.""" + +import collections +import json +import logging +from typing import IO, Optional, Type + +from google.cloud.logging_v2.handlers._helpers import get_request_data +from google.cloud.logging_v2.handlers._monitored_resources import ( + add_resource_labels, + detect_resource, +) +from google.cloud.logging_v2.handlers.transports import ( + BackgroundThreadTransport, + Transport, +) +from google.cloud.logging_v2.resource import Resource + +DEFAULT_LOGGER_NAME = "python" + +"""Defaults for filtering out noisy loggers""" +EXCLUDED_LOGGER_DEFAULTS = ( + "google.api_core.bidi", + "werkzeug", +) + +"""Exclude internal logs from propagating through handlers""" +_INTERNAL_LOGGERS = ( + "google.cloud", + "google.auth", + "google_auth_httplib2", +) + +"""These environments require us to remove extra handlers on setup""" +_CLEAR_HANDLER_RESOURCE_TYPES = ("gae_app", "cloud_function") + + +class CloudLoggingFilter(logging.Filter): + """Python standard ``logging`` Filter class to add Cloud Logging + information to each LogRecord. + + When attached to a LogHandler, each incoming log will be modified + to include new Cloud Logging relevant data. This data can be manually + overwritten using the `extras` argument when writing logs. + """ + + def __init__(self, project=None, default_labels=None): + self.project = project + self.default_labels = default_labels if default_labels else {} + + @staticmethod + def _infer_source_location(record): + """Helper function to infer source location data from a LogRecord. + Will default to record.source_location if already set + """ + if hasattr(record, "source_location"): + return record.source_location + else: + name_map = [ + ("line", "lineno"), + ("file", "pathname"), + ("function", "funcName"), + ] + output = {} + for gcp_name, std_lib_name in name_map: + value = getattr(record, std_lib_name, None) + if value is not None: + output[gcp_name] = value + return output if output else None + + def filter(self, record): + """ + Add new Cloud Logging data to each LogRecord as it comes in + """ + user_labels = getattr(record, "labels", {}) + # infer request data from the environment + ( + inferred_http, + inferred_trace, + inferred_span, + inferred_sampled, + ) = get_request_data() + if inferred_trace is not None and self.project is not None: + # add full path for detected trace + inferred_trace = f"projects/{self.project}/traces/{inferred_trace}" + # set new record values + record._resource = getattr(record, "resource", None) + record._trace = getattr(record, "trace", inferred_trace) or None + record._span_id = getattr(record, "span_id", inferred_span) or None + record._trace_sampled = bool(getattr(record, "trace_sampled", inferred_sampled)) + record._http_request = getattr(record, "http_request", inferred_http) + record._source_location = CloudLoggingFilter._infer_source_location(record) + # add logger name as a label if possible + logger_label = {"python_logger": record.name} if record.name else {} + record._labels = {**logger_label, **self.default_labels, **user_labels} or None + # create string representations for structured logging + record._trace_str = record._trace or "" + record._span_id_str = record._span_id or "" + record._trace_sampled_str = "true" if record._trace_sampled else "false" + record._http_request_str = json.dumps( + record._http_request or {}, ensure_ascii=False + ) + record._source_location_str = json.dumps( + record._source_location or {}, ensure_ascii=False + ) + record._labels_str = json.dumps(record._labels or {}, ensure_ascii=False) + return True + + +class CloudLoggingHandler(logging.StreamHandler): + """Handler that directly makes Cloud Logging API calls. + + This is a Python standard ``logging`` handler using that can be used to + route Python standard logging messages directly to the Stackdriver + Logging API. + + This handler is used when not in GAE or GKE environment. + + This handler supports both an asynchronous and synchronous transport. + + Example: + + .. code-block:: python + + import logging + import google.cloud.logging + from google.cloud.logging_v2.handlers import CloudLoggingHandler + + client = google.cloud.logging.Client() + handler = CloudLoggingHandler(client) + + cloud_logger = logging.getLogger('cloudLogger') + cloud_logger.setLevel(logging.INFO) + cloud_logger.addHandler(handler) + + cloud_logger.error('bad news') # API call + """ + + def __init__( + self, + client, + *, + name: str = DEFAULT_LOGGER_NAME, + transport: Type[Transport] = BackgroundThreadTransport, + resource: Resource = None, + labels: Optional[dict] = None, + stream: Optional[IO] = None, + **kwargs, + ): + """ + Args: + client (~logging_v2.client.Client): + The authenticated Google Cloud Logging client for this + handler to use. + name (str): the name of the custom log in Cloud Logging. + Defaults to 'python'. The name of the Python logger will be represented + in the ``python_logger`` field. + transport (~logging_v2.transports.Transport): + Class for creating new transport objects. It should + extend from the base :class:`.Transport` type and + implement :meth`.Transport.send`. Defaults to + :class:`.BackgroundThreadTransport`. The other + option is :class:`.SyncTransport`. + resource (~logging_v2.resource.Resource): + Resource for this Handler. If not given, will be inferred from the environment. + labels (Optional[dict]): Additional labels to attach to logs. + stream (Optional[IO]): Stream to be used by the handler. + """ + super(CloudLoggingHandler, self).__init__(stream) + if not resource: + # infer the correct monitored resource from the local environment + resource = detect_resource(client.project) + self.name = name + self.client = client + client._handlers.add(self) + self.transport = transport(client, name, resource=resource) + self._transport_open = True + self._transport_cls = transport + self.project_id = client.project + self.resource = resource + self.labels = labels + # add extra keys to log record + log_filter = CloudLoggingFilter(project=self.project_id, default_labels=labels) + self.addFilter(log_filter) + + def emit(self, record): + """Actually log the specified logging record. + + Overrides the default emit behavior of ``StreamHandler``. + + See https://docs.python.org/2/library/logging.html#handler-objects + + Args: + record (logging.LogRecord): The record to be logged. + """ + resource = record._resource or self.resource + labels = record._labels + message = _format_and_parse_message(record, self) + + labels = {**add_resource_labels(resource, record), **(labels or {})} or None + + # send off request + if not self._transport_open: + self.transport = self._transport_cls( + self.client, self.name, resource=self.resource + ) + self._transport_open = True + + self.transport.send( + record, + message, + resource=resource, + labels=labels, + trace=record._trace, + span_id=record._span_id, + trace_sampled=record._trace_sampled, + http_request=record._http_request, + source_location=record._source_location, + ) + + def flush(self): + """Forces the Transport object to submit any pending log records. + + For SyncTransport, this is a no-op. + """ + super(CloudLoggingHandler, self).flush() + if self._transport_open: + self.transport.flush() + + def close(self): + """Closes the log handler and cleans up all Transport objects used.""" + if self._transport_open: + self.transport.close() + self.transport = None + self._transport_open = False + + +def _format_and_parse_message(record, formatter_handler): + """ + Helper function to apply formatting to a LogRecord message, + and attempt to parse encoded JSON into a dictionary object. + + Resulting output will be of type (str | dict | None) + + Args: + record (logging.LogRecord): The record object representing the log + formatter_handler (logging.Handler): The handler used to format the log + """ + passed_json_fields = getattr(record, "json_fields", {}) + # if message is a dictionary, use dictionary directly + if isinstance(record.msg, collections.abc.Mapping): + payload = record.msg + # attach any extra json fields if present + if passed_json_fields and isinstance( + passed_json_fields, collections.abc.Mapping + ): + payload = {**payload, **passed_json_fields} + return payload + # format message string based on superclass + message = formatter_handler.format(record) + try: + # attempt to parse encoded json into dictionary + if message[0] == "{": + json_message = json.loads(message) + if isinstance(json_message, collections.abc.Mapping): + message = json_message + except (json.decoder.JSONDecodeError, IndexError): + # log string is not valid json + pass + # if json_fields was set, create a dictionary using that + if passed_json_fields and isinstance(passed_json_fields, collections.abc.Mapping): + passed_json_fields = passed_json_fields.copy() + if message != "None": + passed_json_fields["message"] = message + return passed_json_fields + # if formatted message contains no content, return None + return message if message != "None" else None + + +def setup_logging( + handler, *, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO +): + """Attach a logging handler to the Python root logger + + Excludes loggers that this library itself uses to avoid + infinite recursion. + + Example: + + .. code-block:: python + + import logging + import google.cloud.logging + from google.cloud.logging_v2.handlers import CloudLoggingHandler + + client = google.cloud.logging.Client() + handler = CloudLoggingHandler(client) + google.cloud.logging.handlers.setup_logging(handler) + logging.getLogger().setLevel(logging.DEBUG) + + logging.error('bad news') # API call + + Args: + handler (logging.handler): the handler to attach to the global handler + excluded_loggers (Optional[Tuple[str]]): The loggers to not attach the handler + to. This will always include the loggers in the + path of the logging client itself. + log_level (Optional[int]): The logging level threshold of the attached logger, + as set by the :meth:`logging.Logger.setLevel` method. Defaults to + :const:`logging.INFO`. + """ + all_excluded_loggers = set(excluded_loggers + _INTERNAL_LOGGERS) + logger = logging.getLogger() + + # remove built-in handlers on App Engine or Cloud Functions environments + if detect_resource().type in _CLEAR_HANDLER_RESOURCE_TYPES: + logger.handlers.clear() + + logger.setLevel(log_level) + logger.addHandler(handler) + for logger_name in all_excluded_loggers: + # prevent excluded loggers from propagating logs to handler + logger = logging.getLogger(logger_name) + logger.propagate = False diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/middleware/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/middleware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bd32e4a901015d5642740efb69bf7a1aad30be9c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/middleware/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2017 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud.logging_v2.handlers.middleware.request import RequestMiddleware + +__all__ = ["RequestMiddleware"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/middleware/request.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/middleware/request.py new file mode 100644 index 0000000000000000000000000000000000000000..3d289938bb67409f46de02d560b552e5c6351a6f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/middleware/request.py @@ -0,0 +1,51 @@ +# Copyright 2017 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Django middleware helper to capture a request. + +The request is stored on a thread-local so that it can be +inspected by other helpers. +""" + +import threading + +_thread_locals = threading.local() + + +def _get_django_request(): + """Get Django request from thread local. + + Returns: + str: Django request + """ + return getattr(_thread_locals, "request", None) + + +def RequestMiddleware(get_response): + """Saves the request in thread local""" + + def middleware(request): + """Called on each request, before Django decides which view to execute. + + Args: + request(django.http.request.HttpRequest): + Django http request. + """ + _thread_locals.request = request + if get_response: + return get_response(request) + else: + return None + + return middleware diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/structured_log.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/structured_log.py new file mode 100644 index 0000000000000000000000000000000000000000..c64d7d3574a72e8ceecaea9b7692c269d061306b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/structured_log.py @@ -0,0 +1,152 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Logging handler for printing formatted structured logs to standard output.""" + +import collections +import json +import logging +import logging.handlers + +import google.cloud.logging_v2 +from google.cloud.logging_v2._instrumentation import _create_diagnostic_entry +from google.cloud.logging_v2.handlers.handlers import ( + CloudLoggingFilter, + _format_and_parse_message, +) + +GCP_FORMAT = ( + "{%(_payload_str)s" + '"severity": "%(levelname)s", ' + '"logging.googleapis.com/labels": %(_labels_str)s, ' + '"logging.googleapis.com/trace": "%(_trace_str)s", ' + '"logging.googleapis.com/spanId": "%(_span_id_str)s", ' + '"logging.googleapis.com/trace_sampled": %(_trace_sampled_str)s, ' + '"logging.googleapis.com/sourceLocation": %(_source_location_str)s, ' + '"httpRequest": %(_http_request_str)s ' + "}" +) + +# reserved fields taken from Structured Logging documentation: +# https://cloud.google.com/logging/docs/structured-logging +GCP_STRUCTURED_LOGGING_FIELDS = frozenset( + { + "severity", + "httpRequest", + "time", + "timestamp", + "timestampSeconds", + "timestampNanos", + "logging.googleapis.com/insertId", + "logging.googleapis.com/labels", + "logging.googleapis.com/operation", + "logging.googleapis.com/sourceLocation", + "logging.googleapis.com/spanId", + "logging.googleapis.com/trace", + "logging.googleapis.com/trace_sampled", + } +) + + +class StructuredLogHandler(logging.StreamHandler): + """Handler to format logs into the Cloud Logging structured log format, + and write them to standard output + """ + + def __init__( + self, + *, + labels=None, + stream=None, + project_id=None, + json_encoder_cls=None, + **kwargs, + ): + """ + Args: + labels (Optional[dict]): Additional labels to attach to logs. + stream (Optional[IO]): Stream to be used by the handler. + project (Optional[str]): Project Id associated with the logs. + json_encoder_cls (Optional[Type[JSONEncoder]]): Custom JSON encoder. Defaults to json.JSONEncoder + """ + super(StructuredLogHandler, self).__init__(stream=stream) + self.project_id = project_id + + # add extra keys to log record + log_filter = CloudLoggingFilter(project=project_id, default_labels=labels) + self.addFilter(log_filter) + + class _Formatter(logging.Formatter): + """Formatter to format log message without traceback""" + + def format(self, record): + """Ignore exception info to avoid duplicating it + https://github.com/googleapis/python-logging/issues/382 + """ + record.message = record.getMessage() + return self.formatMessage(record) + + # make logs appear in GCP structured logging format + self._gcp_formatter = _Formatter(GCP_FORMAT) + + self._json_encoder_cls = json_encoder_cls or json.JSONEncoder + + def format(self, record): + """Format the message into structured log JSON. + Args: + record (logging.LogRecord): The log record. + Returns: + str: A JSON string formatted for GCP structured logging. + """ + payload = None + message = _format_and_parse_message(record, super(StructuredLogHandler, self)) + + if isinstance(message, collections.abc.Mapping): + # remove any special fields + for key in list(message.keys()): + if key in GCP_STRUCTURED_LOGGING_FIELDS: + del message[key] + # if input is a dictionary, encode it as a json string + encoded_msg = json.dumps( + message, ensure_ascii=False, cls=self._json_encoder_cls + ) + # all json.dumps strings should start and end with parentheses + # strip them out to embed these fields in the larger JSON payload + if len(encoded_msg) > 2: + payload = encoded_msg[1:-1] + "," + elif message: + # properly break any formatting in string to make it json safe + encoded_message = json.dumps( + message, ensure_ascii=False, cls=self._json_encoder_cls + ) + payload = '"message": {},'.format(encoded_message) + + record._payload_str = payload or "" + # convert to GCP structured logging format + gcp_payload = self._gcp_formatter.format(record) + return gcp_payload + + def emit(self, record): + if google.cloud.logging_v2._instrumentation_emitted is False: + self.emit_instrumentation_info() + super().emit(record) + + def emit_instrumentation_info(self): + google.cloud.logging_v2._instrumentation_emitted = True + diagnostic_object = _create_diagnostic_entry() + struct_logger = logging.getLogger(__name__) + struct_logger.addHandler(self) + struct_logger.setLevel(logging.INFO) + struct_logger.info(diagnostic_object.payload) + struct_logger.handlers.clear() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..120022bf512dcd6b5f20436693cf6f4355e5f7cb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Transport classes for Python logging integration. + +Currently two options are provided, a synchronous transport that makes +an API call for each log statement, and an asynchronous handler that +sends the API using a :class:`~google.cloud.logging.logger.Batch` object in +the background. +""" + +from google.cloud.logging_v2.handlers.transports.background_thread import ( + BackgroundThreadTransport, +) +from google.cloud.logging_v2.handlers.transports.base import Transport +from google.cloud.logging_v2.handlers.transports.sync import SyncTransport + +__all__ = ["BackgroundThreadTransport", "SyncTransport", "Transport"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/background_thread.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/background_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..021112fdbbc0eec93a0366618cbf11be60f33809 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/background_thread.py @@ -0,0 +1,343 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Transport for Python logging handler + +Uses a background worker to log to Cloud Logging asynchronously. +""" + +from __future__ import print_function + +import atexit +import datetime +import logging +import queue +import sys +import threading +import time + +from google.cloud.logging_v2 import _helpers +from google.cloud.logging_v2.handlers.transports.base import Transport +from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE + +_DEFAULT_GRACE_PERIOD = 5.0 # Seconds +_DEFAULT_MAX_BATCH_SIZE = 10 +_DEFAULT_MAX_LATENCY = 0 # Seconds +_WORKER_THREAD_NAME = "google.cloud.logging.Worker" +_WORKER_TERMINATOR = object() +_LOGGER = logging.getLogger(__name__) + +_CLOSE_THREAD_SHUTDOWN_ERROR_MSG = ( + "CloudLoggingHandler shutting down, cannot send logs entries to Cloud Logging due to " + "inconsistent threading behavior at shutdown. To avoid this issue, flush the logging handler " + "manually or switch to StructuredLogHandler. You can also close the CloudLoggingHandler manually " + "via handler.close or client.close." +) + + +def _get_many(queue_, *, max_items=None, max_latency=0): + """Get multiple items from a Queue. + + Gets at least one (blocking) and at most ``max_items`` items + (non-blocking) from a given Queue. Does not mark the items as done. + + Args: + queue_ (queue.Queue): The Queue to get items from. + max_items (Optional[int]): The maximum number of items to get. + If ``None``, then all available items in the queue are returned. + max_latency (Optional[float]): The maximum number of seconds to wait + for more than one item from a queue. This number includes + the time required to retrieve the first item. + + Returns: + list: items retrieved from the queue + """ + start = time.time() + # Always return at least one item. + items = [queue_.get()] + while max_items is None or len(items) < max_items: + try: + elapsed = time.time() - start + timeout = max(0, max_latency - elapsed) + items.append(queue_.get(timeout=timeout)) + except queue.Empty: + break + return items + + +class _Worker(object): + """A background thread that writes batches of log entries.""" + + def __init__( + self, + cloud_logger, + *, + grace_period=_DEFAULT_GRACE_PERIOD, + max_batch_size=_DEFAULT_MAX_BATCH_SIZE, + max_latency=_DEFAULT_MAX_LATENCY, + ): + """ + Args: + cloud_logger (logging_v2.logger.Logger): + The logger to send entries to. + grace_period (Optional[float]): The amount of time to wait for pending logs to + be submitted when the process is shutting down. + max_batch (Optional[int]): The maximum number of items to send at a time + in the background thread. + max_latency (Optional[float]): The amount of time to wait for new logs before + sending a new batch. It is strongly recommended to keep this smaller + than the grace_period. This means this is effectively the longest + amount of time the background thread will hold onto log entries + before sending them to the server. + """ + self._cloud_logger = cloud_logger + self._grace_period = grace_period + self._max_batch_size = max_batch_size + self._max_latency = max_latency + self._queue = queue.Queue(0) + self._operational_lock = threading.Lock() + self._thread = None + + @property + def is_alive(self): + """Returns True is the background thread is running.""" + return self._thread is not None and self._thread.is_alive() + + def _safely_commit_batch(self, batch): + total_logs = len(batch.entries) + + try: + if total_logs > 0: + batch.commit() + _LOGGER.debug("Submitted %d logs", total_logs) + except Exception: + _LOGGER.error("Failed to submit %d logs.", total_logs, exc_info=True) + + def _thread_main(self): + """The entry point for the worker thread. + + Pulls pending log entries off the queue and writes them in batches to + the Cloud Logger. + """ + _LOGGER.debug("Background thread started.") + + done = False + while not done: + batch = self._cloud_logger.batch() + items = _get_many( + self._queue, + max_items=self._max_batch_size, + max_latency=self._max_latency, + ) + + for item in items: + if item is _WORKER_TERMINATOR: + done = True # Continue processing items. + else: + batch.log(**item) + + # We cannot commit logs upstream if the main thread is shutting down + if threading.main_thread().is_alive(): + self._safely_commit_batch(batch) + + for it in items: + self._queue.task_done() + + _LOGGER.debug("Background thread exited gracefully.") + + def start(self): + """Starts the background thread. + + Additionally, this registers a handler for process exit to attempt + to send any pending log entries before shutdown. + """ + with self._operational_lock: + if self.is_alive: + return + + self._thread = threading.Thread( + target=self._thread_main, name=_WORKER_THREAD_NAME + ) + self._thread.daemon = True + self._thread.start() + atexit.register(self._handle_exit) + + def stop(self, *, grace_period=None): + """Signals the background thread to stop. + + This does not terminate the background thread. It simply queues the + stop signal. If the main process exits before the background thread + processes the stop signal, it will be terminated without finishing + work. The ``grace_period`` parameter will give the background + thread some time to finish processing before this function returns. + + Args: + grace_period (Optional[float]): If specified, this method will + block up to this many seconds to allow the background thread + to finish work before returning. + + Returns: + bool: True if the thread terminated. False if the thread is still + running. + """ + if not self.is_alive: + return True + + with self._operational_lock: + self._queue.put_nowait(_WORKER_TERMINATOR) + + if grace_period is not None: + print("Waiting up to %d seconds." % (grace_period,), file=sys.stderr) + + self._thread.join(timeout=grace_period) + + # Check this before disowning the thread, because after we disown + # the thread is_alive will be False regardless of if the thread + # exited or not. + success = not self.is_alive + + self._thread = None + + return success + + def _close(self, close_msg): + """Callback that attempts to send pending logs before termination if the main thread is alive.""" + if not self.is_alive: + return + + if not self._queue.empty(): + print(close_msg, file=sys.stderr) + + if threading.main_thread().is_alive() and self.stop( + grace_period=self._grace_period + ): + print("Sent all pending logs.", file=sys.stderr) + elif not self._queue.empty(): + print( + "Failed to send %d pending logs." % (self._queue.qsize(),), + file=sys.stderr, + ) + + self._thread = None + + def enqueue(self, record, message, **kwargs): + """Queues a log entry to be written by the background thread. + + Args: + record (logging.LogRecord): Python log record that the handler was called with. + message (str or dict): The message from the ``LogRecord`` after being + formatted by the associated log formatters. + kwargs: Additional optional arguments for the logger + """ + # set python logger name as label if missing + labels = kwargs.pop("labels", {}) + if record.name: + labels["python_logger"] = labels.get("python_logger", record.name) + kwargs["labels"] = labels + # enqueue new entry + queue_entry = { + "message": message, + "severity": _helpers._normalize_severity(record.levelno), + "timestamp": datetime.datetime.fromtimestamp( + record.created, datetime.timezone.utc + ), + } + queue_entry.update(kwargs) + self._queue.put_nowait(queue_entry) + + def flush(self): + """Submit any pending log records.""" + self._queue.join() + + def close(self): + """Signals the worker thread to stop, then closes the transport thread. + + This call will attempt to send pending logs before termination, and + should be followed up by disowning the transport object. + """ + atexit.unregister(self._handle_exit) + self._close( + "Background thread shutting down, attempting to send %d queued log " + "entries to Cloud Logging..." % (self._queue.qsize(),) + ) + + def _handle_exit(self): + """Handle system exit. + + Since we cannot send pending logs during system shutdown due to thread errors, + log an error message to stderr to notify the user. + """ + self._close(_CLOSE_THREAD_SHUTDOWN_ERROR_MSG) + + +class BackgroundThreadTransport(Transport): + """Asynchronous transport that uses a background thread.""" + + def __init__( + self, + client, + name, + *, + grace_period=_DEFAULT_GRACE_PERIOD, + batch_size=_DEFAULT_MAX_BATCH_SIZE, + max_latency=_DEFAULT_MAX_LATENCY, + resource=_GLOBAL_RESOURCE, + **kwargs, + ): + """ + Args: + client (~logging_v2.client.Client): + The Logging client. + name (str): The name of the lgoger. + grace_period (Optional[float]): The amount of time to wait for pending logs to + be submitted when the process is shutting down. + batch_size (Optional[int]): The maximum number of items to send at a time in the + background thread. + max_latency (Optional[float]): The amount of time to wait for new logs before + sending a new batch. It is strongly recommended to keep this smaller + than the grace_period. This means this is effectively the longest + amount of time the background thread will hold onto log entries + before sending them to the server. + resource (Optional[Resource|dict]): The default monitored resource to associate + with logs when not specified + """ + self.client = client + logger = self.client.logger(name, resource=resource) + self.grace_period = grace_period + self.worker = _Worker( + logger, + grace_period=grace_period, + max_batch_size=batch_size, + max_latency=max_latency, + ) + self.worker.start() + + def send(self, record, message, **kwargs): + """Overrides Transport.send(). + + Args: + record (logging.LogRecord): Python log record that the handler was called with. + message (str or dict): The message from the ``LogRecord`` after being + formatted by the associated log formatters. + kwargs: Additional optional arguments for the logger + """ + self.worker.enqueue(record, message, **kwargs) + + def flush(self): + """Submit any pending log records.""" + self.worker.flush() + + def close(self): + """Closes the worker thread.""" + self.worker.close() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..31e8f418affe26e3d2bff89abb0783aecc5bd50d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/base.py @@ -0,0 +1,61 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module containing base class for logging transport.""" + +from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE + + +class Transport(object): + """Base class for Google Cloud Logging handler transports. + + Subclasses of :class:`Transport` must have constructors that accept a + client and name object, and must override :meth:`send`. + """ + + def __init__(self, client, name, resource=_GLOBAL_RESOURCE, **kwargs): + """ + Args: + client (~logging_v2.client.Client): + The Logging client. + name (str): The name of the lgoger. + resource (Optional[Resource|dict]): The default monitored resource to associate + with logs when not specified + """ + super().__init__() + + def send(self, record, message, **kwargs): + """Transport send to be implemented by subclasses. + + Args: + record (logging.LogRecord): Python log record that the handler was called with. + message (str or dict): The message from the ``LogRecord`` after being + formatted by the associated log formatters. + kwargs: Additional optional arguments for the logger + """ + raise NotImplementedError + + def flush(self): + """Submit any pending log records. + + For blocking/sync transports, this is a no-op. + """ + pass + + def close(self): + """Closes the transport and cleans up resources used by it. + + This call should be followed up by disowning the transport. + """ + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/sync.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..6d6bad9f97bac32b529f88ee7eebc6ce1bd18c99 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/handlers/transports/sync.py @@ -0,0 +1,69 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Transport for Python logging handler. + +Logs directly to the Cloud Logging API with a synchronous call. +""" + +from google.cloud.logging_v2 import _helpers +from google.cloud.logging_v2.handlers.transports.base import Transport +from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE + + +class SyncTransport(Transport): + """Basic sychronous transport. + + Uses this library's Logging client to directly make the API call. + """ + + def __init__(self, client, name, resource=_GLOBAL_RESOURCE, **kwargs): + """ + Args: + client (~logging_v2.client.Client): + The Logging client. + name (str): The name of the lgoger. + resource (Optional[Resource|dict]): The default monitored resource to associate + with logs when not specified + """ + self.logger = client.logger(name, resource=resource) + + def send(self, record, message, **kwargs): + """Overrides transport.send(). + + Args: + record (logging.LogRecord): + Python log record that the handler was called with. + message (str or dict): The message from the ``LogRecord`` after being + formatted by the associated log formatters. + kwargs: Additional optional arguments for the logger + """ + # set python logger name as label if missing + labels = kwargs.pop("labels", {}) + if record.name: + labels["python_logger"] = labels.get("python_logger", record.name) + # send log synchronously + self.logger.log( + message, + severity=_helpers._normalize_severity(record.levelno), + labels=labels, + **kwargs, + ) + + def close(self): + """Closes the transport and cleans up resources used by it. + + This call is usually followed up by cleaning up the reference to the transport. + """ + self.logger = None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/logger.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..fbcf7d027ab4b74d58d57958043741bbe7c47349 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/logger.py @@ -0,0 +1,542 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Define API Loggers.""" + +import collections +import re + +import google.protobuf.message +from google.api_core.exceptions import InvalidArgument +from google.rpc.error_details_pb2 import DebugInfo + +import google.cloud.logging_v2 +from google.cloud.logging_v2._helpers import _add_defaults_to_filter +from google.cloud.logging_v2._instrumentation import _add_instrumentation +from google.cloud.logging_v2.entries import ( + LogEntry, + ProtobufEntry, + StructEntry, + TextEntry, +) +from google.cloud.logging_v2.handlers._monitored_resources import detect_resource +from google.cloud.logging_v2.resource import Resource + +_GLOBAL_RESOURCE = Resource(type="global", labels={}) + + +_OUTBOUND_ENTRY_FIELDS = ( # (name, default) + ("type_", None), + ("log_name", None), + ("payload", None), + ("labels", None), + ("insert_id", None), + ("severity", None), + ("http_request", None), + ("timestamp", None), + ("resource", _GLOBAL_RESOURCE), + ("trace", None), + ("span_id", None), + ("trace_sampled", None), + ("source_location", None), +) + +_STRUCT_EXTRACTABLE_FIELDS = ["severity", "trace", "span_id"] + + +class Logger(object): + """Loggers represent named targets for log entries. + + See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs + """ + + def __init__(self, name, client, *, labels=None, resource=None): + """ + Args: + name (str): The name of the logger. + client (~logging_v2.client.Client): + A client which holds credentials and project configuration + for the logger (which requires a project). + resource (Optional[~logging_v2.Resource]): a monitored resource object + representing the resource the code was run on. If not given, will + be inferred from the environment. + labels (Optional[dict]): Mapping of default labels for entries written + via this logger. + + """ + if not resource: + # infer the correct monitored resource from the local environment + resource = detect_resource(client.project) + self.name = name + self._client = client + self.labels = labels + self.default_resource = resource + + @property + def client(self): + """Clent bound to the logger.""" + return self._client + + @property + def project(self): + """Project bound to the logger.""" + return self._client.project + + @property + def full_name(self): + """Fully-qualified name used in logging APIs""" + return f"projects/{self.project}/logs/{self.name}" + + @property + def path(self): + """URI path for use in logging APIs""" + return f"/{self.full_name}" + + def _require_client(self, client): + """Check client or verify over-ride. Also sets ``parent``. + + Args: + client (Union[None, ~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + + Returns: + ~logging_v2.client.Client: The client passed in + or the currently bound client. + """ + if client is None: + client = self._client + return client + + def batch(self, *, client=None): + """Return a batch to use as a context manager. + + Args: + client (Union[None, ~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + + Returns: + Batch: A batch to use as a context manager. + """ + client = self._require_client(client) + return Batch(self, client) + + def _do_log(self, client, _entry_class, payload=None, **kw): + """Helper for :meth:`log_empty`, :meth:`log_text`, etc.""" + client = self._require_client(client) + + # Apply defaults + kw["log_name"] = kw.pop("log_name", self.full_name) + kw["labels"] = kw.pop("labels", self.labels) + kw["resource"] = kw.pop("resource", self.default_resource) + + severity = kw.get("severity", None) + if isinstance(severity, str): + # convert severity to upper case, as expected by enum definition + kw["severity"] = severity.upper() + + if isinstance(kw["resource"], collections.abc.Mapping): + # if resource was passed as a dict, attempt to parse it into a + # Resource object + try: + kw["resource"] = Resource(**kw["resource"]) + except TypeError as e: + # dict couldn't be parsed as a Resource + raise TypeError("invalid resource dict") from e + + if payload is not None: + entry = _entry_class(payload=payload, **kw) + else: + entry = _entry_class(**kw) + + api_repr = entry.to_api_repr() + entries = [api_repr] + + if google.cloud.logging_v2._instrumentation_emitted is False: + entries = _add_instrumentation(entries, **kw) + google.cloud.logging_v2._instrumentation_emitted = True + # partial_success is true to avoid dropping instrumentation logs + client.logging_api.write_entries(entries, partial_success=True) + + def log_empty(self, *, client=None, **kw): + """Log an empty message + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + kw (Optional[dict]): additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self._do_log(client, LogEntry, **kw) + + def log_text(self, text, *, client=None, **kw): + """Log a text message + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write + + Args: + text (str): the log message + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + kw (Optional[dict]): additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self._do_log(client, TextEntry, text, **kw) + + def log_struct(self, info, *, client=None, **kw): + """Logs a dictionary message. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write + + The message must be able to be serializable to a Protobuf Struct. + It must be a dictionary of strings to one of the following: + + - :class:`str` + - :class:`int` + - :class:`float` + - :class:`bool` + - :class:`list[str|float|int|bool|list|dict|None]` + - :class:`dict[str, str|float|int|bool|list|dict|None]` + + For more details on Protobuf structs, see https://protobuf.dev/reference/protobuf/google.protobuf/#value. + If the provided dictionary cannot be serialized into a Protobuf struct, + it will not be logged, and a :class:`ValueError` will be raised. + + Args: + info (dict[str, str|float|int|bool|list|dict|None]): + the log entry information. + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + kw (Optional[dict]): additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + + Raises: + ValueError: + if the dictionary message provided cannot be serialized into a Protobuf + struct. + """ + for field in _STRUCT_EXTRACTABLE_FIELDS: + # attempt to copy relevant fields from the payload into the LogEntry body + if field in info and field not in kw: + kw[field] = info[field] + self._do_log(client, StructEntry, info, **kw) + + def log_proto(self, message, *, client=None, **kw): + """Log a protobuf message + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list + + Args: + message (google.protobuf.message.Message): + The protobuf message to be logged. + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + kw (Optional[dict]): additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self._do_log(client, ProtobufEntry, message, **kw) + + def log(self, message=None, *, client=None, **kw): + """Log an arbitrary message. Type will be inferred based on the input. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list + + Args: + message (Optional[str or dict or google.protobuf.Message]): The message. to log + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + kw (Optional[dict]): additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + if isinstance(message, google.protobuf.message.Message): + self.log_proto(message, client=client, **kw) + elif isinstance(message, collections.abc.Mapping): + self.log_struct(message, client=client, **kw) + elif isinstance(message, str): + self.log_text(message, client=client, **kw) + else: + self._do_log(client, LogEntry, message, **kw) + + def delete(self, logger_name=None, *, client=None): + """Delete all entries in a logger via a DELETE request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete + + Args: + logger_name (Optional[str]): The resource name of the log to delete: + + :: + + "projects/[PROJECT_ID]/logs/[LOG_ID]" + "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + "folders/[FOLDER_ID]/logs/[LOG_ID]" + + ``[LOG_ID]`` must be URL-encoded. For example, + ``"projects/my-project-id/logs/syslog"``, + ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. + If not passed, defaults to the project bound to the client. + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current logger. + """ + client = self._require_client(client) + if logger_name is None: + logger_name = self.full_name + client.logging_api.logger_delete(logger_name) + + def list_entries( + self, + *, + resource_names=None, + filter_=None, + order_by=None, + max_results=None, + page_size=None, + page_token=None, + ): + """Return a generator of log entry resources. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list + + Args: + resource_names (Optional[Sequence[str]]): Names of one or more parent resources + from which to retrieve log entries: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + If not passed, defaults to the project bound to the client. + filter_ (Optional[str]): a filter expression. See + https://cloud.google.com/logging/docs/view/advanced_filters + By default, a 24 hour filter is applied. + order_by (Optional[str]): One of :data:`~logging_v2.ASCENDING` + or :data:`~logging_v2.DESCENDING`. + max_results (Optional[int]): + Optional. The maximum number of entries to return. + Non-positive values are treated as 0. If None, uses API defaults. + page_size (int): number of entries to fetch in each API call. Although + requests are paged internally, logs are returned by the generator + one at a time. If not passed, defaults to a value set by the API. + page_token (str): opaque marker for the starting "page" of entries. If not + passed, the API will return the first page of entries. + Returns: + Generator[~logging_v2.LogEntry] + """ + + if resource_names is None: + resource_names = [f"projects/{self.project}"] + + log_filter = f"logName={self.full_name}" + if filter_ is not None: + filter_ = f"{filter_} AND {log_filter}" + else: + filter_ = log_filter + filter_ = _add_defaults_to_filter(filter_) + return self.client.list_entries( + resource_names=resource_names, + filter_=filter_, + order_by=order_by, + max_results=max_results, + page_size=page_size, + page_token=page_token, + ) + + +class Batch(object): + def __init__(self, logger, client, *, resource=None): + """Context manager: collect entries to log via a single API call. + + Helper returned by :meth:`Logger.batch` + + Args: + logger (logging_v2.logger.Logger): + the logger to which entries will be logged. + client (~logging_V2.client.Client): + The client to use. + resource (Optional[~logging_v2.resource.Resource]): + Monitored resource of the batch, defaults + to None, which requires that every entry should have a + resource specified. Since the methods used to write + entries default the entry's resource to the global + resource type, this parameter is only required + if explicitly set to None. If no entries' resource are + set to None, this parameter will be ignored on the server. + """ + self.logger = logger + self.entries = [] + self.client = client + self.resource = resource + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_type is None: + self.commit() + + def log_empty(self, **kw): + """Add a entry without payload to be logged during :meth:`commit`. + + Args: + kw (Optional[dict]): Additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self.entries.append(LogEntry(**kw)) + + def log_text(self, text, **kw): + """Add a text entry to be logged during :meth:`commit`. + + Args: + text (str): the text entry + kw (Optional[dict]): Additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self.entries.append(TextEntry(payload=text, **kw)) + + def log_struct(self, info, **kw): + """Add a struct entry to be logged during :meth:`commit`. + + The message must be able to be serializable to a Protobuf Struct. + It must be a dictionary of strings to one of the following: + + - :class:`str` + - :class:`int` + - :class:`float` + - :class:`bool` + - :class:`list[str|float|int|bool|list|dict|None]` + - :class:`dict[str, str|float|int|bool|list|dict|None]` + + For more details on Protobuf structs, see https://protobuf.dev/reference/protobuf/google.protobuf/#value. + If the provided dictionary cannot be serialized into a Protobuf struct, + it will not be logged, and a :class:`ValueError` will be raised during :meth:`commit`. + + Args: + info (dict[str, str|float|int|bool|list|dict|None]): The struct entry, + kw (Optional[dict]): Additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self.entries.append(StructEntry(payload=info, **kw)) + + def log_proto(self, message, **kw): + """Add a protobuf entry to be logged during :meth:`commit`. + + Args: + message (google.protobuf.Message): The protobuf entry. + kw (Optional[dict]): Additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + self.entries.append(ProtobufEntry(payload=message, **kw)) + + def log(self, message=None, **kw): + """Add an arbitrary message to be logged during :meth:`commit`. + Type will be inferred based on the input message. + + Args: + message (Optional[str or dict or google.protobuf.Message]): The message. to log + kw (Optional[dict]): Additional keyword arguments for the entry. + See :class:`~logging_v2.entries.LogEntry`. + """ + entry_type = LogEntry + if isinstance(message, google.protobuf.message.Message): + entry_type = ProtobufEntry + elif isinstance(message, collections.abc.Mapping): + entry_type = StructEntry + elif isinstance(message, str): + entry_type = TextEntry + self.entries.append(entry_type(payload=message, **kw)) + + def commit(self, *, client=None, partial_success=True): + """Send saved log entries as a single API call. + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current batch. + partial_success (Optional[bool]): + Whether a batch's valid entries should be written even + if some other entry failed due to a permanent error such + as INVALID_ARGUMENT or PERMISSION_DENIED. + + Raises: + ValueError: + if one of the messages in the batch cannot be successfully parsed. + """ + if client is None: + client = self.client + + kwargs = {"logger_name": self.logger.full_name} + + if self.resource is not None: + kwargs["resource"] = self.resource._to_dict() + + if self.logger.labels is not None: + kwargs["labels"] = self.logger.labels + + entries = [entry.to_api_repr() for entry in self.entries] + try: + client.logging_api.write_entries( + entries, partial_success=partial_success, **kwargs + ) + except InvalidArgument as e: + # InvalidArgument is often sent when a log is too large + # attempt to attach extra contex on which log caused error + self._append_context_to_error(e) + raise e + del self.entries[:] + + def _append_context_to_error(self, err): + """ + Attempts to Modify `write_entries` exception messages to contain + context on which log in the batch caused the error. + + Best-effort basis. If another exception occurs while processing the + input exception, the input will be left unmodified + + Args: + err (~google.api_core.exceptions.InvalidArgument): + The original exception object + """ + try: + # find debug info proto if in details + debug_info = next(x for x in err.details if isinstance(x, DebugInfo)) + # parse out the index of the faulty entry + error_idx = re.search("(?<=key: )[0-9]+", debug_info.detail).group(0) + # find the faulty entry object + found_entry = self.entries[int(error_idx)] + str_entry = str(found_entry.to_api_repr()) + # modify error message to contain extra context + err.message = f"{err.message}: {str_entry:.2000}..." + except Exception: + # if parsing fails, abort changes and leave err unmodified + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/metric.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/metric.py new file mode 100644 index 0000000000000000000000000000000000000000..167165c973e426ff2e76993dab074b8b180f61a2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/metric.py @@ -0,0 +1,180 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Define Cloud Logging API Metrics.""" + +from google.cloud.exceptions import NotFound + + +class Metric(object): + """Metrics represent named filters for log entries. + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics + """ + + def __init__(self, name, *, filter_=None, client=None, description=""): + """ + Args: + name (str): The name of the metric. + filter_ (str): the advanced logs filter expression defining the entries + tracked by the metric. If not passed, the instance should + already exist, to be refreshed via :meth:`reload`. + client (Optional[~logging_v2.client.Client]): A client which holds + credentials and project configuration for the sink (which requires a project). + description (Optional[str]): An optional description of the metric. + + """ + self.name = name + self._client = client + self.filter_ = filter_ + self.description = description + + @property + def client(self): + """Clent bound to the logger.""" + return self._client + + @property + def project(self): + """Project bound to the logger.""" + return self._client.project + + @property + def full_name(self): + """Fully-qualified name used in metric APIs""" + return f"projects/{self.project}/metrics/{self.name}" + + @property + def path(self): + """URL path for the metric's APIs""" + return f"/{self.full_name}" + + @classmethod + def from_api_repr(cls, resource, client): + """Construct a metric given its API representation + + Args: + resource (dict): metric resource representation returned from the API + client (~logging_v2.client.Client): Client which holds + credentials and project configuration for the sink. + + Returns: + google.cloud.logging_v2.metric.Metric + """ + metric_name = resource["name"] + filter_ = resource["filter"] + description = resource.get("description", "") + return cls(metric_name, filter_=filter_, client=client, description=description) + + def _require_client(self, client): + """Check client or verify over-ride. Also sets ``parent``. + + Args: + client (Union[None, ~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + + Returns: + google.cloud.logging_v2.client.Client: The client passed in + or the currently bound client. + """ + if client is None: + client = self._client + return client + + def create(self, *, client=None): + """Create the metric via a PUT request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + """ + client = self._require_client(client) + client.metrics_api.metric_create( + self.project, self.name, self.filter_, self.description + ) + + def exists(self, *, client=None): + """Test for the existence of the metric via a GET request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/get + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + + Returns: + bool: Boolean indicating existence of the metric. + """ + client = self._require_client(client) + + try: + client.metrics_api.metric_get(self.project, self.name) + except NotFound: + return False + else: + return True + + def reload(self, *, client=None): + """API call: sync local metric configuration via a GET request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/get + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + """ + client = self._require_client(client) + data = client.metrics_api.metric_get(self.project, self.name) + self.description = data.get("description", "") + self.filter_ = data["filter"] + + def update(self, *, client=None): + """API call: update metric configuration via a PUT request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/update + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + """ + client = self._require_client(client) + client.metrics_api.metric_update( + self.project, self.name, self.filter_, self.description + ) + + def delete(self, *, client=None): + """API call: delete a metric via a DELETE request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/delete + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + """ + client = self._require_client(client) + client.metrics_api.metric_delete(self.project, self.name) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..6c7420d0d9cb016b1dfe8d5b1e260dfbd6f1d30e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-logging package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/resource.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..eed5ca5fa5e672627d32be56348c0ec174676539 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/resource.py @@ -0,0 +1,51 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Monitored Resource for the Google Logging API V2.""" + +import collections + + +class Resource(collections.namedtuple("Resource", "type labels")): + """A monitored resource identified by specifying values for all labels. + + Attributes: + type (str): The resource type name. + labels (dict): A mapping from label names to values for all labels + enumerated in the associated :class:`ResourceDescriptor`. + """ + + __slots__ = () + + @classmethod + def _from_dict(cls, info): + """Construct a resource object from the parsed JSON representation. + + Args: + info (dict): A ``dict`` parsed from the JSON wire-format representation. + + Returns: + Resource: A resource object. + """ + return cls(type=info["type"], labels=info.get("labels", {})) + + def _to_dict(self): + """Build a dictionary ready to be serialized to the JSON format. + + Returns: + dict: + A dict representation of the object that can be written to + the API. + """ + return {"type": self.type, "labels": self.labels} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..986f6a0c801c374f32f13468a4d2928655364f7d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import ConfigServiceV2AsyncClient +from .client import ConfigServiceV2Client + +__all__ = ( + "ConfigServiceV2Client", + "ConfigServiceV2AsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..1b1cf6d24445f956d63f42067bfa01c299a0537d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/async_client.py @@ -0,0 +1,4251 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +import uuid +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.logging_v2.services.config_service_v2 import pagers +from google.cloud.logging_v2.types import logging_config + +from .client import ConfigServiceV2Client +from .transports.base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class ConfigServiceV2AsyncClient: + """Service for configuring sinks used to route log entries.""" + + _client: ConfigServiceV2Client + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ConfigServiceV2Client.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ConfigServiceV2Client._DEFAULT_UNIVERSE + + cmek_settings_path = staticmethod(ConfigServiceV2Client.cmek_settings_path) + parse_cmek_settings_path = staticmethod( + ConfigServiceV2Client.parse_cmek_settings_path + ) + link_path = staticmethod(ConfigServiceV2Client.link_path) + parse_link_path = staticmethod(ConfigServiceV2Client.parse_link_path) + log_bucket_path = staticmethod(ConfigServiceV2Client.log_bucket_path) + parse_log_bucket_path = staticmethod(ConfigServiceV2Client.parse_log_bucket_path) + log_exclusion_path = staticmethod(ConfigServiceV2Client.log_exclusion_path) + parse_log_exclusion_path = staticmethod( + ConfigServiceV2Client.parse_log_exclusion_path + ) + log_sink_path = staticmethod(ConfigServiceV2Client.log_sink_path) + parse_log_sink_path = staticmethod(ConfigServiceV2Client.parse_log_sink_path) + log_view_path = staticmethod(ConfigServiceV2Client.log_view_path) + parse_log_view_path = staticmethod(ConfigServiceV2Client.parse_log_view_path) + settings_path = staticmethod(ConfigServiceV2Client.settings_path) + parse_settings_path = staticmethod(ConfigServiceV2Client.parse_settings_path) + common_billing_account_path = staticmethod( + ConfigServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ConfigServiceV2Client.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ConfigServiceV2Client.common_folder_path) + parse_common_folder_path = staticmethod( + ConfigServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + ConfigServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + ConfigServiceV2Client.parse_common_organization_path + ) + common_project_path = staticmethod(ConfigServiceV2Client.common_project_path) + parse_common_project_path = staticmethod( + ConfigServiceV2Client.parse_common_project_path + ) + common_location_path = staticmethod(ConfigServiceV2Client.common_location_path) + parse_common_location_path = staticmethod( + ConfigServiceV2Client.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConfigServiceV2AsyncClient: The constructed client. + """ + sa_info_func = ( + ConfigServiceV2Client.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ConfigServiceV2AsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConfigServiceV2AsyncClient: The constructed client. + """ + sa_file_func = ( + ConfigServiceV2Client.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(ConfigServiceV2AsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ConfigServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ConfigServiceV2Transport: + """Returns the transport used by the client instance. + + Returns: + ConfigServiceV2Transport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = ConfigServiceV2Client.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the config service v2 async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ConfigServiceV2Transport,Callable[..., ConfigServiceV2Transport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ConfigServiceV2Transport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ConfigServiceV2Client( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.logging_v2.ConfigServiceV2AsyncClient`.", + extra={ + "serviceName": "google.logging.v2.ConfigServiceV2", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.logging.v2.ConfigServiceV2", + "credentialsType": None, + }, + ) + + async def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsAsyncPager: + r"""Lists log buckets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_buckets(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListBucketsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_buckets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListBucketsRequest, dict]]): + The request object. The parameters to ``ListBuckets``. + parent (:class:`str`): + Required. The parent resource whose buckets are to be + listed: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + + Note: The locations portion of the resource must be + specified, but supplying the character ``-`` in place of + [LOCATION_ID] will return all buckets. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListBucketsAsyncPager: + The response from ListBuckets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListBucketsRequest): + request = logging_config.ListBucketsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_buckets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBucketsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: + r"""Gets a log bucket. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetBucketRequest( + name="name_value", + ) + + # Make the request + response = await client.get_bucket(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetBucketRequest, dict]]): + The request object. The parameters to ``GetBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogBucket: + Describes a repository in which log + entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetBucketRequest): + request = logging_config.GetBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_bucket + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a log bucket asynchronously that can be used + to store log entries. + After a bucket has been created, the bucket's location + cannot be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_bucket_async(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.CreateBucketRequest( + parent="parent_value", + bucket_id="bucket_id_value", + ) + + # Make the request + operation = client.create_bucket_async(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateBucketRequest, dict]]): + The request object. The parameters to ``CreateBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.LogBucket` + Describes a repository in which log entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateBucketRequest): + request = logging_config.CreateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_bucket_async + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + logging_config.LogBucket, + metadata_type=logging_config.BucketMetadata, + ) + + # Done; return the response. + return response + + async def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a log bucket asynchronously. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_bucket_async(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.UpdateBucketRequest( + name="name_value", + ) + + # Make the request + operation = client.update_bucket_async(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateBucketRequest, dict]]): + The request object. The parameters to ``UpdateBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.LogBucket` + Describes a repository in which log entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateBucketRequest): + request = logging_config.UpdateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_bucket_async + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + logging_config.LogBucket, + metadata_type=logging_config.BucketMetadata, + ) + + # Done; return the response. + return response + + async def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: + r"""Creates a log bucket that can be used to store log + entries. After a bucket has been created, the bucket's + location cannot be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.CreateBucketRequest( + parent="parent_value", + bucket_id="bucket_id_value", + ) + + # Make the request + response = await client.create_bucket(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateBucketRequest, dict]]): + The request object. The parameters to ``CreateBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogBucket: + Describes a repository in which log + entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateBucketRequest): + request = logging_config.CreateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_bucket + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: + r"""Updates a log bucket. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.UpdateBucketRequest( + name="name_value", + ) + + # Make the request + response = await client.update_bucket(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateBucketRequest, dict]]): + The request object. The parameters to ``UpdateBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogBucket: + Describes a repository in which log + entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateBucketRequest): + request = logging_config.UpdateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_bucket + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a log bucket. + + Changes the bucket's ``lifecycle_state`` to the + ``DELETE_REQUESTED`` state. After 7 days, the bucket will be + purged and all log entries in the bucket will be permanently + deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteBucketRequest( + name="name_value", + ) + + # Make the request + await client.delete_bucket(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteBucketRequest, dict]]): + The request object. The parameters to ``DeleteBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteBucketRequest): + request = logging_config.DeleteBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_bucket + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Undeletes a log bucket. A bucket that has been + deleted can be undeleted within the grace period of 7 + days. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_undelete_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.UndeleteBucketRequest( + name="name_value", + ) + + # Make the request + await client.undelete_bucket(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UndeleteBucketRequest, dict]]): + The request object. The parameters to ``UndeleteBucket``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UndeleteBucketRequest): + request = logging_config.UndeleteBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_bucket + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsAsyncPager: + r"""Lists views on a log bucket. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_views(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListViewsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_views(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListViewsRequest, dict]]): + The request object. The parameters to ``ListViews``. + parent (:class:`str`): + Required. The bucket whose views are to be listed: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListViewsAsyncPager: + The response from ListViews. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListViewsRequest): + request = logging_config.ListViewsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_views + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListViewsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: + r"""Gets a view on a log bucket.. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_view(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetViewRequest( + name="name_value", + ) + + # Make the request + response = await client.get_view(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetViewRequest, dict]]): + The request object. The parameters to ``GetView``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogView: + Describes a view over log entries in + a bucket. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetViewRequest): + request = logging_config.GetViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: + r"""Creates a view over log entries in a log bucket. A + bucket may contain a maximum of 30 views. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_view(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.CreateViewRequest( + parent="parent_value", + view_id="view_id_value", + ) + + # Make the request + response = await client.create_view(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateViewRequest, dict]]): + The request object. The parameters to ``CreateView``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogView: + Describes a view over log entries in + a bucket. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateViewRequest): + request = logging_config.CreateViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: + r"""Updates a view on a log bucket. This method replaces the + following fields in the existing view with values from the new + view: ``filter``. If an ``UNAVAILABLE`` error is returned, this + indicates that system is not in a state where it can update the + view. If this occurs, please try again in a few minutes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_view(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.UpdateViewRequest( + name="name_value", + ) + + # Make the request + response = await client.update_view(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateViewRequest, dict]]): + The request object. The parameters to ``UpdateView``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogView: + Describes a view over log entries in + a bucket. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateViewRequest): + request = logging_config.UpdateViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is + returned, this indicates that system is not in a state where it + can delete the view. If this occurs, please try again in a few + minutes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_view(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteViewRequest( + name="name_value", + ) + + # Make the request + await client.delete_view(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteViewRequest, dict]]): + The request object. The parameters to ``DeleteView``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteViewRequest): + request = logging_config.DeleteViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksAsyncPager: + r"""Lists sinks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_sinks(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListSinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sinks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListSinksRequest, dict]]): + The request object. The parameters to ``ListSinks``. + parent (:class:`str`): + Required. The parent resource whose sinks are to be + listed: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListSinksAsyncPager: + Result returned from ListSinks. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListSinksRequest): + request = logging_config.ListSinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sinks + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: + r"""Gets a sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_sink(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetSinkRequest( + sink_name="sink_name_value", + ) + + # Make the request + response = await client.get_sink(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetSinkRequest, dict]]): + The request object. The parameters to ``GetSink``. + sink_name (:class:`str`): + Required. The resource name of the sink: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + + This corresponds to the ``sink_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogSink: + Describes a sink used to export log + entries to one of the following + destinations in any project: a Cloud + Storage bucket, a BigQuery dataset, a + Pub/Sub topic or a Cloud Logging log + bucket. A logs filter controls which log + entries are exported. The sink must be + created within a project, organization, + billing account, or folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [sink_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetSinkRequest): + request = logging_config.GetSinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sink_name is not None: + request.sink_name = sink_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_sink] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: + r"""Creates a sink that exports specified log entries to a + destination. The export of newly-ingested log entries begins + immediately, unless the sink's ``writer_identity`` is not + permitted to write to the destination. A sink can export log + entries only from the resource owning the sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_sink(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + sink = logging_v2.LogSink() + sink.name = "name_value" + sink.destination = "destination_value" + + request = logging_v2.CreateSinkRequest( + parent="parent_value", + sink=sink, + ) + + # Make the request + response = await client.create_sink(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateSinkRequest, dict]]): + The request object. The parameters to ``CreateSink``. + parent (:class:`str`): + Required. The resource in which to create the sink: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + For examples: + + ``"projects/my-project"`` ``"organizations/123456789"`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sink (:class:`google.cloud.logging_v2.types.LogSink`): + Required. The new sink, whose ``name`` parameter is a + sink identifier that is not already in use. + + This corresponds to the ``sink`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogSink: + Describes a sink used to export log + entries to one of the following + destinations in any project: a Cloud + Storage bucket, a BigQuery dataset, a + Pub/Sub topic or a Cloud Logging log + bucket. A logs filter controls which log + entries are exported. The sink must be + created within a project, organization, + billing account, or folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, sink] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateSinkRequest): + request = logging_config.CreateSinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sink is not None: + request.sink = sink + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sink + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: + r"""Updates a sink. This method replaces the following fields in the + existing sink with values from the new sink: ``destination``, + and ``filter``. + + The updated sink might also have a new ``writer_identity``; see + the ``unique_writer_identity`` field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_sink(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + sink = logging_v2.LogSink() + sink.name = "name_value" + sink.destination = "destination_value" + + request = logging_v2.UpdateSinkRequest( + sink_name="sink_name_value", + sink=sink, + ) + + # Make the request + response = await client.update_sink(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateSinkRequest, dict]]): + The request object. The parameters to ``UpdateSink``. + sink_name (:class:`str`): + Required. The full resource name of the sink to update, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + + This corresponds to the ``sink_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sink (:class:`google.cloud.logging_v2.types.LogSink`): + Required. The updated sink, whose name is the same + identifier that appears as part of ``sink_name``. + + This corresponds to the ``sink`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask that specifies the fields in + ``sink`` that need an update. A sink field will be + overwritten if, and only if, it is in the update mask. + ``name`` and output only fields cannot be updated. + + An empty ``updateMask`` is temporarily treated as using + the following mask for backwards compatibility purposes: + + ``destination,filter,includeChildren`` + + At some point in the future, behavior will be removed + and specifying an empty ``updateMask`` will be an error. + + For a detailed ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + + For example: ``updateMask=filter`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogSink: + Describes a sink used to export log + entries to one of the following + destinations in any project: a Cloud + Storage bucket, a BigQuery dataset, a + Pub/Sub topic or a Cloud Logging log + bucket. A logs filter controls which log + entries are exported. The sink must be + created within a project, organization, + billing account, or folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [sink_name, sink, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateSinkRequest): + request = logging_config.UpdateSinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sink_name is not None: + request.sink_name = sink_name + if sink is not None: + request.sink = sink + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sink + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a sink. If the sink has a unique ``writer_identity``, + then that service account is also deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_sink(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteSinkRequest( + sink_name="sink_name_value", + ) + + # Make the request + await client.delete_sink(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteSinkRequest, dict]]): + The request object. The parameters to ``DeleteSink``. + sink_name (:class:`str`): + Required. The full resource name of the sink to delete, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + + This corresponds to the ``sink_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [sink_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteSinkRequest): + request = logging_config.DeleteSinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sink_name is not None: + request.sink_name = sink_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sink + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Asynchronously creates a linked dataset in BigQuery + which makes it possible to use BigQuery to read the logs + stored in the log bucket. A log bucket may currently + only contain one link. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_link(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.CreateLinkRequest( + parent="parent_value", + link_id="link_id_value", + ) + + # Make the request + operation = client.create_link(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateLinkRequest, dict]]): + The request object. The parameters to CreateLink. + parent (:class:`str`): + Required. The full resource name of the bucket to create + a link for. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + link (:class:`google.cloud.logging_v2.types.Link`): + Required. The new link. + This corresponds to the ``link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + link_id (:class:`str`): + Required. The ID to use for the link. The link_id can + have up to 100 characters. A valid link_id must only + have alphanumeric characters and underscores within it. + + This corresponds to the ``link_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.Link` Describes a + link connected to an analytics enabled bucket. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, link, link_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateLinkRequest): + request = logging_config.CreateLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if link is not None: + request.link = link + if link_id is not None: + request.link_id = link_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_link + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + logging_config.Link, + metadata_type=logging_config.LinkMetadata, + ) + + # Done; return the response. + return response + + async def delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a link. This will also delete the + corresponding BigQuery linked dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_link(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteLinkRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_link(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteLinkRequest, dict]]): + The request object. The parameters to DeleteLink. + name (:class:`str`): + Required. The full resource name of the link to delete. + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteLinkRequest): + request = logging_config.DeleteLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_link + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=logging_config.LinkMetadata, + ) + + # Done; return the response. + return response + + async def list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksAsyncPager: + r"""Lists links. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_links(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_links(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListLinksRequest, dict]]): + The request object. The parameters to ListLinks. + parent (:class:`str`): + Required. The parent resource whose links are to be + listed: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/ + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListLinksAsyncPager: + The response from ListLinks. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListLinksRequest): + request = logging_config.ListLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_links + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: + r"""Gets a link. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_link(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetLinkRequest( + name="name_value", + ) + + # Make the request + response = await client.get_link(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetLinkRequest, dict]]): + The request object. The parameters to GetLink. + name (:class:`str`): + Required. The resource name of the link: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID] + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.Link: + Describes a link connected to an + analytics enabled bucket. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetLinkRequest): + request = logging_config.GetLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsAsyncPager: + r"""Lists all the exclusions on the \_Default sink in a parent + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_exclusions(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListExclusionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_exclusions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListExclusionsRequest, dict]]): + The request object. The parameters to ``ListExclusions``. + parent (:class:`str`): + Required. The parent resource whose exclusions are to be + listed. + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListExclusionsAsyncPager: + Result returned from ListExclusions. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListExclusionsRequest): + request = logging_config.ListExclusionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_exclusions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListExclusionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: + r"""Gets the description of an exclusion in the \_Default sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetExclusionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_exclusion(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetExclusionRequest, dict]]): + The request object. The parameters to ``GetExclusion``. + name (:class:`str`): + Required. The resource name of an existing exclusion: + + :: + + "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + + For example: + + ``"projects/my-project/exclusions/my-exclusion"`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogExclusion: + Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of + log entries, you can use exclusions to reduce your + chargeable logs. Note that exclusions on + organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify + the Required sink or exclude logs from it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetExclusionRequest): + request = logging_config.GetExclusionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_exclusion + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: + r"""Creates a new exclusion in the \_Default sink in a specified + parent resource. Only log entries belonging to that resource can + be excluded. You can have up to 10 exclusions in a resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + exclusion = logging_v2.LogExclusion() + exclusion.name = "name_value" + exclusion.filter = "filter_value" + + request = logging_v2.CreateExclusionRequest( + parent="parent_value", + exclusion=exclusion, + ) + + # Make the request + response = await client.create_exclusion(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateExclusionRequest, dict]]): + The request object. The parameters to ``CreateExclusion``. + parent (:class:`str`): + Required. The parent resource in which to create the + exclusion: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + For examples: + + ``"projects/my-logging-project"`` + ``"organizations/123456789"`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + exclusion (:class:`google.cloud.logging_v2.types.LogExclusion`): + Required. The new exclusion, whose ``name`` parameter is + an exclusion name that is not already used in the parent + resource. + + This corresponds to the ``exclusion`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogExclusion: + Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of + log entries, you can use exclusions to reduce your + chargeable logs. Note that exclusions on + organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify + the Required sink or exclude logs from it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, exclusion] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateExclusionRequest): + request = logging_config.CreateExclusionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if exclusion is not None: + request.exclusion = exclusion + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_exclusion + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: + r"""Changes one or more properties of an existing exclusion in the + \_Default sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + exclusion = logging_v2.LogExclusion() + exclusion.name = "name_value" + exclusion.filter = "filter_value" + + request = logging_v2.UpdateExclusionRequest( + name="name_value", + exclusion=exclusion, + ) + + # Make the request + response = await client.update_exclusion(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateExclusionRequest, dict]]): + The request object. The parameters to ``UpdateExclusion``. + name (:class:`str`): + Required. The resource name of the exclusion to update: + + :: + + "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + + For example: + + ``"projects/my-project/exclusions/my-exclusion"`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + exclusion (:class:`google.cloud.logging_v2.types.LogExclusion`): + Required. New values for the existing exclusion. Only + the fields specified in ``update_mask`` are relevant. + + This corresponds to the ``exclusion`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A non-empty list of fields to change in the + existing exclusion. New values for the fields are taken + from the corresponding fields in the + [LogExclusion][google.logging.v2.LogExclusion] included + in this request. Fields not mentioned in ``update_mask`` + are not changed and are ignored in the request. + + For example, to change the filter and description of an + exclusion, specify an ``update_mask`` of + ``"filter,description"``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogExclusion: + Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of + log entries, you can use exclusions to reduce your + chargeable logs. Note that exclusions on + organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify + the Required sink or exclude logs from it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, exclusion, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateExclusionRequest): + request = logging_config.UpdateExclusionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if exclusion is not None: + request.exclusion = exclusion + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_exclusion + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an exclusion in the \_Default sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteExclusionRequest( + name="name_value", + ) + + # Make the request + await client.delete_exclusion(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteExclusionRequest, dict]]): + The request object. The parameters to ``DeleteExclusion``. + name (:class:`str`): + Required. The resource name of an existing exclusion to + delete: + + :: + + "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + + For example: + + ``"projects/my-project/exclusions/my-exclusion"`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteExclusionRequest): + request = logging_config.DeleteExclusionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_exclusion + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: + r"""Gets the Logging CMEK settings for the given resource. + + Note: CMEK for the Log Router can be configured for Google Cloud + projects, folders, organizations and billing accounts. Once + configured for an organization, it applies to all projects and + folders in the Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_cmek_settings(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetCmekSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cmek_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetCmekSettingsRequest, dict]]): + The request object. The parameters to + [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.CmekSettings: + Describes the customer-managed encryption key (CMEK) settings associated with + a project, folder, organization, billing account, or + flexible resource. + + Note: CMEK for the Log Router can currently only be + configured for Google Cloud organizations. Once + configured, it applies to all projects and folders in + the Google Cloud organization. + + See [Enabling CMEK for Log + Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + for more information. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetCmekSettingsRequest): + request = logging_config.GetCmekSettingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_cmek_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: + r"""Updates the Log Router CMEK settings for the given resource. + + Note: CMEK for the Log Router can currently only be configured + for Google Cloud organizations. Once configured, it applies to + all projects and folders in the Google Cloud organization. + + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_cmek_settings(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.UpdateCmekSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.update_cmek_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateCmekSettingsRequest, dict]]): + The request object. The parameters to + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.CmekSettings: + Describes the customer-managed encryption key (CMEK) settings associated with + a project, folder, organization, billing account, or + flexible resource. + + Note: CMEK for the Log Router can currently only be + configured for Google Cloud organizations. Once + configured, it applies to all projects and folders in + the Google Cloud organization. + + See [Enabling CMEK for Log + Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + for more information. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateCmekSettingsRequest): + request = logging_config.UpdateCmekSettingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_cmek_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: + r"""Gets the Log Router settings for the given resource. + + Note: Settings for the Log Router can be get for Google Cloud + projects, folders, organizations and billing accounts. Currently + it can only be configured for organizations. Once configured for + an organization, it applies to all projects and folders in the + Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_settings(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetSettingsRequest, dict]]): + The request object. The parameters to + [GetSettings][google.logging.v2.ConfigServiceV2.GetSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + name (:class:`str`): + Required. The resource for which to retrieve settings. + + :: + + "projects/[PROJECT_ID]/settings" + "organizations/[ORGANIZATION_ID]/settings" + "billingAccounts/[BILLING_ACCOUNT_ID]/settings" + "folders/[FOLDER_ID]/settings" + + For example: + + ``"organizations/12345/settings"`` + + Note: Settings for the Log Router can be get for Google + Cloud projects, folders, organizations and billing + accounts. Currently it can only be configured for + organizations. Once configured for an organization, it + applies to all projects and folders in the Google Cloud + organization. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.Settings: + Describes the settings associated + with a project, folder, organization, + billing account, or flexible resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetSettingsRequest): + request = logging_config.GetSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: + r"""Updates the Log Router settings for the given resource. + + Note: Settings for the Log Router can currently only be + configured for Google Cloud organizations. Once configured, it + applies to all projects and folders in the Google Cloud + organization. + + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. 4) ``location_id`` + is not supported by Logging. 5) ``location_id`` violate + OrgPolicy. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_settings(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.UpdateSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.update_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateSettingsRequest, dict]]): + The request object. The parameters to + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + settings (:class:`google.cloud.logging_v2.types.Settings`): + Required. The settings to update. + + See `Enabling CMEK for Log + Router `__ + for more information. + + This corresponds to the ``settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask identifying which fields from + ``settings`` should be updated. A field will be + overwritten if and only if it is in the update mask. + Output only fields cannot be updated. + + See [FieldMask][google.protobuf.FieldMask] for more + information. + + For example: ``"updateMask=kmsKeyName"`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.Settings: + Describes the settings associated + with a project, folder, organization, + billing account, or flexible resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [settings, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateSettingsRequest): + request = logging_config.UpdateSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if settings is not None: + request.settings = settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Copies a set of log entries from a log bucket to a + Cloud Storage bucket. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_copy_log_entries(): + # Create a client + client = logging_v2.ConfigServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.CopyLogEntriesRequest( + name="name_value", + destination="destination_value", + ) + + # Make the request + operation = client.copy_log_entries(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CopyLogEntriesRequest, dict]]): + The request object. The parameters to CopyLogEntries. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.CopyLogEntriesResponse` + Response type for CopyLogEntries long running + operations. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CopyLogEntriesRequest): + request = logging_config.CopyLogEntriesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.copy_log_entries + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + logging_config.CopyLogEntriesResponse, + metadata_type=logging_config.CopyLogEntriesMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "ConfigServiceV2AsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("ConfigServiceV2AsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/client.py new file mode 100644 index 0000000000000000000000000000000000000000..242bb3ff5779938c52596dad171c8228eea711cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/client.py @@ -0,0 +1,4717 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import uuid +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.logging_v2.services.config_service_v2 import pagers +from google.cloud.logging_v2.types import logging_config + +from .transports.base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from .transports.grpc import ConfigServiceV2GrpcTransport +from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport + + +class ConfigServiceV2ClientMeta(type): + """Metaclass for the ConfigServiceV2 client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] + _transport_registry["grpc"] = ConfigServiceV2GrpcTransport + _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ConfigServiceV2Client(metaclass=ConfigServiceV2ClientMeta): + """Service for configuring sinks used to route log entries.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "logging.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConfigServiceV2Client: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConfigServiceV2Client: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ConfigServiceV2Transport: + """Returns the transport used by the client instance. + + Returns: + ConfigServiceV2Transport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cmek_settings_path( + project: str, + ) -> str: + """Returns a fully-qualified cmek_settings string.""" + return "projects/{project}/cmekSettings".format( + project=project, + ) + + @staticmethod + def parse_cmek_settings_path(path: str) -> Dict[str, str]: + """Parses a cmek_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def link_path( + project: str, + location: str, + bucket: str, + link: str, + ) -> str: + """Returns a fully-qualified link string.""" + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( + project=project, + location=location, + bucket=bucket, + link=link, + ) + + @staticmethod + def parse_link_path(path: str) -> Dict[str, str]: + """Parses a link path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def log_bucket_path( + project: str, + location: str, + bucket: str, + ) -> str: + """Returns a fully-qualified log_bucket string.""" + return "projects/{project}/locations/{location}/buckets/{bucket}".format( + project=project, + location=location, + bucket=bucket, + ) + + @staticmethod + def parse_log_bucket_path(path: str) -> Dict[str, str]: + """Parses a log_bucket path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def log_exclusion_path( + project: str, + exclusion: str, + ) -> str: + """Returns a fully-qualified log_exclusion string.""" + return "projects/{project}/exclusions/{exclusion}".format( + project=project, + exclusion=exclusion, + ) + + @staticmethod + def parse_log_exclusion_path(path: str) -> Dict[str, str]: + """Parses a log_exclusion path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def log_sink_path( + project: str, + sink: str, + ) -> str: + """Returns a fully-qualified log_sink string.""" + return "projects/{project}/sinks/{sink}".format( + project=project, + sink=sink, + ) + + @staticmethod + def parse_log_sink_path(path: str) -> Dict[str, str]: + """Parses a log_sink path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def log_view_path( + project: str, + location: str, + bucket: str, + view: str, + ) -> str: + """Returns a fully-qualified log_view string.""" + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( + project=project, + location=location, + bucket=bucket, + view=view, + ) + + @staticmethod + def parse_log_view_path(path: str) -> Dict[str, str]: + """Parses a log_view path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def settings_path( + project: str, + ) -> str: + """Returns a fully-qualified settings string.""" + return "projects/{project}/settings".format( + project=project, + ) + + @staticmethod + def parse_settings_path(path: str) -> Dict[str, str]: + """Parses a settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/settings$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ConfigServiceV2Client._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ConfigServiceV2Client._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ConfigServiceV2Client._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ConfigServiceV2Client._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the config service v2 client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ConfigServiceV2Transport,Callable[..., ConfigServiceV2Transport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ConfigServiceV2Transport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + ConfigServiceV2Client._read_environment_variables() + ) + self._client_cert_source = ConfigServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ConfigServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ConfigServiceV2Transport) + if transport_provided: + # transport is a ConfigServiceV2Transport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(ConfigServiceV2Transport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or ConfigServiceV2Client._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] + ] = ( + ConfigServiceV2Client.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ConfigServiceV2Transport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.logging_v2.ConfigServiceV2Client`.", + extra={ + "serviceName": "google.logging.v2.ConfigServiceV2", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.logging.v2.ConfigServiceV2", + "credentialsType": None, + }, + ) + + def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: + r"""Lists log buckets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_buckets(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListBucketsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_buckets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListBucketsRequest, dict]): + The request object. The parameters to ``ListBuckets``. + parent (str): + Required. The parent resource whose buckets are to be + listed: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + + Note: The locations portion of the resource must be + specified, but supplying the character ``-`` in place of + [LOCATION_ID] will return all buckets. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListBucketsPager: + The response from ListBuckets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListBucketsRequest): + request = logging_config.ListBucketsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_buckets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBucketsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: + r"""Gets a log bucket. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetBucketRequest( + name="name_value", + ) + + # Make the request + response = client.get_bucket(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetBucketRequest, dict]): + The request object. The parameters to ``GetBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogBucket: + Describes a repository in which log + entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetBucketRequest): + request = logging_config.GetBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_bucket] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a log bucket asynchronously that can be used + to store log entries. + After a bucket has been created, the bucket's location + cannot be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_bucket_async(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.CreateBucketRequest( + parent="parent_value", + bucket_id="bucket_id_value", + ) + + # Make the request + operation = client.create_bucket_async(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateBucketRequest, dict]): + The request object. The parameters to ``CreateBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.LogBucket` + Describes a repository in which log entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateBucketRequest): + request = logging_config.CreateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_bucket_async] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + logging_config.LogBucket, + metadata_type=logging_config.BucketMetadata, + ) + + # Done; return the response. + return response + + def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a log bucket asynchronously. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_bucket_async(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.UpdateBucketRequest( + name="name_value", + ) + + # Make the request + operation = client.update_bucket_async(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateBucketRequest, dict]): + The request object. The parameters to ``UpdateBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.LogBucket` + Describes a repository in which log entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateBucketRequest): + request = logging_config.UpdateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_bucket_async] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + logging_config.LogBucket, + metadata_type=logging_config.BucketMetadata, + ) + + # Done; return the response. + return response + + def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: + r"""Creates a log bucket that can be used to store log + entries. After a bucket has been created, the bucket's + location cannot be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.CreateBucketRequest( + parent="parent_value", + bucket_id="bucket_id_value", + ) + + # Make the request + response = client.create_bucket(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateBucketRequest, dict]): + The request object. The parameters to ``CreateBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogBucket: + Describes a repository in which log + entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateBucketRequest): + request = logging_config.CreateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_bucket] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: + r"""Updates a log bucket. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.UpdateBucketRequest( + name="name_value", + ) + + # Make the request + response = client.update_bucket(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateBucketRequest, dict]): + The request object. The parameters to ``UpdateBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogBucket: + Describes a repository in which log + entries are stored. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateBucketRequest): + request = logging_config.UpdateBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_bucket] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a log bucket. + + Changes the bucket's ``lifecycle_state`` to the + ``DELETE_REQUESTED`` state. After 7 days, the bucket will be + purged and all log entries in the bucket will be permanently + deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteBucketRequest( + name="name_value", + ) + + # Make the request + client.delete_bucket(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteBucketRequest, dict]): + The request object. The parameters to ``DeleteBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteBucketRequest): + request = logging_config.DeleteBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_bucket] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Undeletes a log bucket. A bucket that has been + deleted can be undeleted within the grace period of 7 + days. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_undelete_bucket(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.UndeleteBucketRequest( + name="name_value", + ) + + # Make the request + client.undelete_bucket(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.UndeleteBucketRequest, dict]): + The request object. The parameters to ``UndeleteBucket``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UndeleteBucketRequest): + request = logging_config.UndeleteBucketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_bucket] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: + r"""Lists views on a log bucket. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_views(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListViewsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_views(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListViewsRequest, dict]): + The request object. The parameters to ``ListViews``. + parent (str): + Required. The bucket whose views are to be listed: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListViewsPager: + The response from ListViews. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListViewsRequest): + request = logging_config.ListViewsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_views] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListViewsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: + r"""Gets a view on a log bucket.. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_view(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetViewRequest( + name="name_value", + ) + + # Make the request + response = client.get_view(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetViewRequest, dict]): + The request object. The parameters to ``GetView``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogView: + Describes a view over log entries in + a bucket. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetViewRequest): + request = logging_config.GetViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: + r"""Creates a view over log entries in a log bucket. A + bucket may contain a maximum of 30 views. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_view(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.CreateViewRequest( + parent="parent_value", + view_id="view_id_value", + ) + + # Make the request + response = client.create_view(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateViewRequest, dict]): + The request object. The parameters to ``CreateView``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogView: + Describes a view over log entries in + a bucket. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateViewRequest): + request = logging_config.CreateViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: + r"""Updates a view on a log bucket. This method replaces the + following fields in the existing view with values from the new + view: ``filter``. If an ``UNAVAILABLE`` error is returned, this + indicates that system is not in a state where it can update the + view. If this occurs, please try again in a few minutes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_view(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.UpdateViewRequest( + name="name_value", + ) + + # Make the request + response = client.update_view(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateViewRequest, dict]): + The request object. The parameters to ``UpdateView``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogView: + Describes a view over log entries in + a bucket. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateViewRequest): + request = logging_config.UpdateViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is + returned, this indicates that system is not in a state where it + can delete the view. If this occurs, please try again in a few + minutes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_view(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteViewRequest( + name="name_value", + ) + + # Make the request + client.delete_view(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteViewRequest, dict]): + The request object. The parameters to ``DeleteView``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteViewRequest): + request = logging_config.DeleteViewRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: + r"""Lists sinks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_sinks(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListSinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sinks(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListSinksRequest, dict]): + The request object. The parameters to ``ListSinks``. + parent (str): + Required. The parent resource whose sinks are to be + listed: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListSinksPager: + Result returned from ListSinks. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListSinksRequest): + request = logging_config.ListSinksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_sinks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: + r"""Gets a sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_sink(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetSinkRequest( + sink_name="sink_name_value", + ) + + # Make the request + response = client.get_sink(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetSinkRequest, dict]): + The request object. The parameters to ``GetSink``. + sink_name (str): + Required. The resource name of the sink: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + + This corresponds to the ``sink_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogSink: + Describes a sink used to export log + entries to one of the following + destinations in any project: a Cloud + Storage bucket, a BigQuery dataset, a + Pub/Sub topic or a Cloud Logging log + bucket. A logs filter controls which log + entries are exported. The sink must be + created within a project, organization, + billing account, or folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [sink_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetSinkRequest): + request = logging_config.GetSinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sink_name is not None: + request.sink_name = sink_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_sink] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: + r"""Creates a sink that exports specified log entries to a + destination. The export of newly-ingested log entries begins + immediately, unless the sink's ``writer_identity`` is not + permitted to write to the destination. A sink can export log + entries only from the resource owning the sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_sink(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + sink = logging_v2.LogSink() + sink.name = "name_value" + sink.destination = "destination_value" + + request = logging_v2.CreateSinkRequest( + parent="parent_value", + sink=sink, + ) + + # Make the request + response = client.create_sink(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateSinkRequest, dict]): + The request object. The parameters to ``CreateSink``. + parent (str): + Required. The resource in which to create the sink: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + For examples: + + ``"projects/my-project"`` ``"organizations/123456789"`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sink (google.cloud.logging_v2.types.LogSink): + Required. The new sink, whose ``name`` parameter is a + sink identifier that is not already in use. + + This corresponds to the ``sink`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogSink: + Describes a sink used to export log + entries to one of the following + destinations in any project: a Cloud + Storage bucket, a BigQuery dataset, a + Pub/Sub topic or a Cloud Logging log + bucket. A logs filter controls which log + entries are exported. The sink must be + created within a project, organization, + billing account, or folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, sink] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateSinkRequest): + request = logging_config.CreateSinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sink is not None: + request.sink = sink + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sink] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: + r"""Updates a sink. This method replaces the following fields in the + existing sink with values from the new sink: ``destination``, + and ``filter``. + + The updated sink might also have a new ``writer_identity``; see + the ``unique_writer_identity`` field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_sink(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + sink = logging_v2.LogSink() + sink.name = "name_value" + sink.destination = "destination_value" + + request = logging_v2.UpdateSinkRequest( + sink_name="sink_name_value", + sink=sink, + ) + + # Make the request + response = client.update_sink(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateSinkRequest, dict]): + The request object. The parameters to ``UpdateSink``. + sink_name (str): + Required. The full resource name of the sink to update, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + + This corresponds to the ``sink_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sink (google.cloud.logging_v2.types.LogSink): + Required. The updated sink, whose name is the same + identifier that appears as part of ``sink_name``. + + This corresponds to the ``sink`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that specifies the fields in + ``sink`` that need an update. A sink field will be + overwritten if, and only if, it is in the update mask. + ``name`` and output only fields cannot be updated. + + An empty ``updateMask`` is temporarily treated as using + the following mask for backwards compatibility purposes: + + ``destination,filter,includeChildren`` + + At some point in the future, behavior will be removed + and specifying an empty ``updateMask`` will be an error. + + For a detailed ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + + For example: ``updateMask=filter`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogSink: + Describes a sink used to export log + entries to one of the following + destinations in any project: a Cloud + Storage bucket, a BigQuery dataset, a + Pub/Sub topic or a Cloud Logging log + bucket. A logs filter controls which log + entries are exported. The sink must be + created within a project, organization, + billing account, or folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [sink_name, sink, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateSinkRequest): + request = logging_config.UpdateSinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sink_name is not None: + request.sink_name = sink_name + if sink is not None: + request.sink = sink + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_sink] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a sink. If the sink has a unique ``writer_identity``, + then that service account is also deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_sink(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteSinkRequest( + sink_name="sink_name_value", + ) + + # Make the request + client.delete_sink(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteSinkRequest, dict]): + The request object. The parameters to ``DeleteSink``. + sink_name (str): + Required. The full resource name of the sink to delete, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + + This corresponds to the ``sink_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [sink_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteSinkRequest): + request = logging_config.DeleteSinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sink_name is not None: + request.sink_name = sink_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_sink] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Asynchronously creates a linked dataset in BigQuery + which makes it possible to use BigQuery to read the logs + stored in the log bucket. A log bucket may currently + only contain one link. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_link(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.CreateLinkRequest( + parent="parent_value", + link_id="link_id_value", + ) + + # Make the request + operation = client.create_link(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateLinkRequest, dict]): + The request object. The parameters to CreateLink. + parent (str): + Required. The full resource name of the bucket to create + a link for. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + link (google.cloud.logging_v2.types.Link): + Required. The new link. + This corresponds to the ``link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + link_id (str): + Required. The ID to use for the link. The link_id can + have up to 100 characters. A valid link_id must only + have alphanumeric characters and underscores within it. + + This corresponds to the ``link_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.Link` Describes a + link connected to an analytics enabled bucket. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, link, link_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateLinkRequest): + request = logging_config.CreateLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if link is not None: + request.link = link + if link_id is not None: + request.link_id = link_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + logging_config.Link, + metadata_type=logging_config.LinkMetadata, + ) + + # Done; return the response. + return response + + def delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a link. This will also delete the + corresponding BigQuery linked dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_link(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteLinkRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_link(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteLinkRequest, dict]): + The request object. The parameters to DeleteLink. + name (str): + Required. The full resource name of the link to delete. + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteLinkRequest): + request = logging_config.DeleteLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=logging_config.LinkMetadata, + ) + + # Done; return the response. + return response + + def list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: + r"""Lists links. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_links(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_links(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListLinksRequest, dict]): + The request object. The parameters to ListLinks. + parent (str): + Required. The parent resource whose links are to be + listed: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/ + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListLinksPager: + The response from ListLinks. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListLinksRequest): + request = logging_config.ListLinksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_links] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: + r"""Gets a link. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_link(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetLinkRequest( + name="name_value", + ) + + # Make the request + response = client.get_link(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetLinkRequest, dict]): + The request object. The parameters to GetLink. + name (str): + Required. The resource name of the link: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID] + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.Link: + Describes a link connected to an + analytics enabled bucket. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetLinkRequest): + request = logging_config.GetLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: + r"""Lists all the exclusions on the \_Default sink in a parent + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_exclusions(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListExclusionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_exclusions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListExclusionsRequest, dict]): + The request object. The parameters to ``ListExclusions``. + parent (str): + Required. The parent resource whose exclusions are to be + listed. + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.config_service_v2.pagers.ListExclusionsPager: + Result returned from ListExclusions. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.ListExclusionsRequest): + request = logging_config.ListExclusionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_exclusions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListExclusionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: + r"""Gets the description of an exclusion in the \_Default sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetExclusionRequest( + name="name_value", + ) + + # Make the request + response = client.get_exclusion(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetExclusionRequest, dict]): + The request object. The parameters to ``GetExclusion``. + name (str): + Required. The resource name of an existing exclusion: + + :: + + "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + + For example: + + ``"projects/my-project/exclusions/my-exclusion"`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogExclusion: + Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of + log entries, you can use exclusions to reduce your + chargeable logs. Note that exclusions on + organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify + the Required sink or exclude logs from it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetExclusionRequest): + request = logging_config.GetExclusionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_exclusion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: + r"""Creates a new exclusion in the \_Default sink in a specified + parent resource. Only log entries belonging to that resource can + be excluded. You can have up to 10 exclusions in a resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + exclusion = logging_v2.LogExclusion() + exclusion.name = "name_value" + exclusion.filter = "filter_value" + + request = logging_v2.CreateExclusionRequest( + parent="parent_value", + exclusion=exclusion, + ) + + # Make the request + response = client.create_exclusion(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateExclusionRequest, dict]): + The request object. The parameters to ``CreateExclusion``. + parent (str): + Required. The parent resource in which to create the + exclusion: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + For examples: + + ``"projects/my-logging-project"`` + ``"organizations/123456789"`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + exclusion (google.cloud.logging_v2.types.LogExclusion): + Required. The new exclusion, whose ``name`` parameter is + an exclusion name that is not already used in the parent + resource. + + This corresponds to the ``exclusion`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogExclusion: + Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of + log entries, you can use exclusions to reduce your + chargeable logs. Note that exclusions on + organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify + the Required sink or exclude logs from it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, exclusion] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CreateExclusionRequest): + request = logging_config.CreateExclusionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if exclusion is not None: + request.exclusion = exclusion + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_exclusion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: + r"""Changes one or more properties of an existing exclusion in the + \_Default sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + exclusion = logging_v2.LogExclusion() + exclusion.name = "name_value" + exclusion.filter = "filter_value" + + request = logging_v2.UpdateExclusionRequest( + name="name_value", + exclusion=exclusion, + ) + + # Make the request + response = client.update_exclusion(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateExclusionRequest, dict]): + The request object. The parameters to ``UpdateExclusion``. + name (str): + Required. The resource name of the exclusion to update: + + :: + + "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + + For example: + + ``"projects/my-project/exclusions/my-exclusion"`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + exclusion (google.cloud.logging_v2.types.LogExclusion): + Required. New values for the existing exclusion. Only + the fields specified in ``update_mask`` are relevant. + + This corresponds to the ``exclusion`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A non-empty list of fields to change in the + existing exclusion. New values for the fields are taken + from the corresponding fields in the + [LogExclusion][google.logging.v2.LogExclusion] included + in this request. Fields not mentioned in ``update_mask`` + are not changed and are ignored in the request. + + For example, to change the filter and description of an + exclusion, specify an ``update_mask`` of + ``"filter,description"``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogExclusion: + Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of + log entries, you can use exclusions to reduce your + chargeable logs. Note that exclusions on + organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify + the Required sink or exclude logs from it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, exclusion, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateExclusionRequest): + request = logging_config.UpdateExclusionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if exclusion is not None: + request.exclusion = exclusion + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_exclusion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an exclusion in the \_Default sink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_exclusion(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteExclusionRequest( + name="name_value", + ) + + # Make the request + client.delete_exclusion(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteExclusionRequest, dict]): + The request object. The parameters to ``DeleteExclusion``. + name (str): + Required. The resource name of an existing exclusion to + delete: + + :: + + "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + + For example: + + ``"projects/my-project/exclusions/my-exclusion"`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.DeleteExclusionRequest): + request = logging_config.DeleteExclusionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_exclusion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: + r"""Gets the Logging CMEK settings for the given resource. + + Note: CMEK for the Log Router can be configured for Google Cloud + projects, folders, organizations and billing accounts. Once + configured for an organization, it applies to all projects and + folders in the Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_cmek_settings(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetCmekSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_cmek_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetCmekSettingsRequest, dict]): + The request object. The parameters to + [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.CmekSettings: + Describes the customer-managed encryption key (CMEK) settings associated with + a project, folder, organization, billing account, or + flexible resource. + + Note: CMEK for the Log Router can currently only be + configured for Google Cloud organizations. Once + configured, it applies to all projects and folders in + the Google Cloud organization. + + See [Enabling CMEK for Log + Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + for more information. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetCmekSettingsRequest): + request = logging_config.GetCmekSettingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_cmek_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: + r"""Updates the Log Router CMEK settings for the given resource. + + Note: CMEK for the Log Router can currently only be configured + for Google Cloud organizations. Once configured, it applies to + all projects and folders in the Google Cloud organization. + + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_cmek_settings(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.UpdateCmekSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.update_cmek_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateCmekSettingsRequest, dict]): + The request object. The parameters to + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.CmekSettings: + Describes the customer-managed encryption key (CMEK) settings associated with + a project, folder, organization, billing account, or + flexible resource. + + Note: CMEK for the Log Router can currently only be + configured for Google Cloud organizations. Once + configured, it applies to all projects and folders in + the Google Cloud organization. + + See [Enabling CMEK for Log + Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + for more information. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateCmekSettingsRequest): + request = logging_config.UpdateCmekSettingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_cmek_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: + r"""Gets the Log Router settings for the given resource. + + Note: Settings for the Log Router can be get for Google Cloud + projects, folders, organizations and billing accounts. Currently + it can only be configured for organizations. Once configured for + an organization, it applies to all projects and folders in the + Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_settings(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetSettingsRequest, dict]): + The request object. The parameters to + [GetSettings][google.logging.v2.ConfigServiceV2.GetSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + name (str): + Required. The resource for which to retrieve settings. + + :: + + "projects/[PROJECT_ID]/settings" + "organizations/[ORGANIZATION_ID]/settings" + "billingAccounts/[BILLING_ACCOUNT_ID]/settings" + "folders/[FOLDER_ID]/settings" + + For example: + + ``"organizations/12345/settings"`` + + Note: Settings for the Log Router can be get for Google + Cloud projects, folders, organizations and billing + accounts. Currently it can only be configured for + organizations. Once configured for an organization, it + applies to all projects and folders in the Google Cloud + organization. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.Settings: + Describes the settings associated + with a project, folder, organization, + billing account, or flexible resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.GetSettingsRequest): + request = logging_config.GetSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: + r"""Updates the Log Router settings for the given resource. + + Note: Settings for the Log Router can currently only be + configured for Google Cloud organizations. Once configured, it + applies to all projects and folders in the Google Cloud + organization. + + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. 4) ``location_id`` + is not supported by Logging. 5) ``location_id`` violate + OrgPolicy. + + See `Enabling CMEK for Log + Router `__ + for more information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_settings(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.UpdateSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.update_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateSettingsRequest, dict]): + The request object. The parameters to + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + settings (google.cloud.logging_v2.types.Settings): + Required. The settings to update. + + See `Enabling CMEK for Log + Router `__ + for more information. + + This corresponds to the ``settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask identifying which fields from + ``settings`` should be updated. A field will be + overwritten if and only if it is in the update mask. + Output only fields cannot be updated. + + See [FieldMask][google.protobuf.FieldMask] for more + information. + + For example: ``"updateMask=kmsKeyName"`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.Settings: + Describes the settings associated + with a project, folder, organization, + billing account, or flexible resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [settings, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.UpdateSettingsRequest): + request = logging_config.UpdateSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if settings is not None: + request.settings = settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Copies a set of log entries from a log bucket to a + Cloud Storage bucket. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_copy_log_entries(): + # Create a client + client = logging_v2.ConfigServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.CopyLogEntriesRequest( + name="name_value", + destination="destination_value", + ) + + # Make the request + operation = client.copy_log_entries(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CopyLogEntriesRequest, dict]): + The request object. The parameters to CopyLogEntries. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.logging_v2.types.CopyLogEntriesResponse` + Response type for CopyLogEntries long running + operations. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_config.CopyLogEntriesRequest): + request = logging_config.CopyLogEntriesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.copy_log_entries] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + logging_config.CopyLogEntriesResponse, + metadata_type=logging_config.CopyLogEntriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ConfigServiceV2Client": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ConfigServiceV2Client",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..2083d04239142020399a720abe1aeb6d52a32d74 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/pagers.py @@ -0,0 +1,821 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.logging_v2.types import logging_config + + +class ListBucketsPager: + """A pager for iterating through ``list_buckets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListBucketsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``buckets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBuckets`` requests and continue to iterate + through the ``buckets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListBucketsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging_config.ListBucketsResponse], + request: logging_config.ListBucketsRequest, + response: logging_config.ListBucketsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListBucketsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListBucketsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListBucketsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging_config.ListBucketsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[logging_config.LogBucket]: + for page in self.pages: + yield from page.buckets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBucketsAsyncPager: + """A pager for iterating through ``list_buckets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListBucketsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``buckets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBuckets`` requests and continue to iterate + through the ``buckets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListBucketsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging_config.ListBucketsResponse]], + request: logging_config.ListBucketsRequest, + response: logging_config.ListBucketsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListBucketsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListBucketsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListBucketsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging_config.ListBucketsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[logging_config.LogBucket]: + async def async_generator(): + async for page in self.pages: + for response in page.buckets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListViewsPager: + """A pager for iterating through ``list_views`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListViewsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``views`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListViews`` requests and continue to iterate + through the ``views`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListViewsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging_config.ListViewsResponse], + request: logging_config.ListViewsRequest, + response: logging_config.ListViewsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListViewsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListViewsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListViewsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging_config.ListViewsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[logging_config.LogView]: + for page in self.pages: + yield from page.views + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListViewsAsyncPager: + """A pager for iterating through ``list_views`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListViewsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``views`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListViews`` requests and continue to iterate + through the ``views`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListViewsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging_config.ListViewsResponse]], + request: logging_config.ListViewsRequest, + response: logging_config.ListViewsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListViewsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListViewsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListViewsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging_config.ListViewsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[logging_config.LogView]: + async def async_generator(): + async for page in self.pages: + for response in page.views: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSinksPager: + """A pager for iterating through ``list_sinks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListSinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sinks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSinks`` requests and continue to iterate + through the ``sinks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListSinksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging_config.ListSinksResponse], + request: logging_config.ListSinksRequest, + response: logging_config.ListSinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListSinksRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListSinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListSinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging_config.ListSinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[logging_config.LogSink]: + for page in self.pages: + yield from page.sinks + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSinksAsyncPager: + """A pager for iterating through ``list_sinks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListSinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sinks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSinks`` requests and continue to iterate + through the ``sinks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListSinksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging_config.ListSinksResponse]], + request: logging_config.ListSinksRequest, + response: logging_config.ListSinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListSinksRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListSinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListSinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging_config.ListSinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[logging_config.LogSink]: + async def async_generator(): + async for page in self.pages: + for response in page.sinks: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLinksPager: + """A pager for iterating through ``list_links`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLinks`` requests and continue to iterate + through the ``links`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLinksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging_config.ListLinksResponse], + request: logging_config.ListLinksRequest, + response: logging_config.ListLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLinksRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging_config.ListLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[logging_config.Link]: + for page in self.pages: + yield from page.links + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLinksAsyncPager: + """A pager for iterating through ``list_links`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLinks`` requests and continue to iterate + through the ``links`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLinksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging_config.ListLinksResponse]], + request: logging_config.ListLinksRequest, + response: logging_config.ListLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLinksRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging_config.ListLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[logging_config.Link]: + async def async_generator(): + async for page in self.pages: + for response in page.links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExclusionsPager: + """A pager for iterating through ``list_exclusions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListExclusionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``exclusions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExclusions`` requests and continue to iterate + through the ``exclusions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListExclusionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging_config.ListExclusionsResponse], + request: logging_config.ListExclusionsRequest, + response: logging_config.ListExclusionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListExclusionsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListExclusionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListExclusionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging_config.ListExclusionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[logging_config.LogExclusion]: + for page in self.pages: + yield from page.exclusions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExclusionsAsyncPager: + """A pager for iterating through ``list_exclusions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListExclusionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``exclusions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExclusions`` requests and continue to iterate + through the ``exclusions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListExclusionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging_config.ListExclusionsResponse]], + request: logging_config.ListExclusionsRequest, + response: logging_config.ListExclusionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListExclusionsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListExclusionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_config.ListExclusionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging_config.ListExclusionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[logging_config.LogExclusion]: + async def async_generator(): + async for page in self.pages: + for response in page.exclusions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..790c53bfdcdd2caa59010a05876f6fa9b3ef9539 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConfigServiceV2Transport +from .grpc import ConfigServiceV2GrpcTransport +from .grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] +_transport_registry["grpc"] = ConfigServiceV2GrpcTransport +_transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport + +__all__ = ( + "ConfigServiceV2Transport", + "ConfigServiceV2GrpcTransport", + "ConfigServiceV2GrpcAsyncIOTransport", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d0b5bbd47c876e177ff41c4cadb90105d3ad0124 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -0,0 +1,758 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2.types import logging_config + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ConfigServiceV2Transport(abc.ABC): + """Abstract transport class for ConfigServiceV2.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + ) + + DEFAULT_HOST: str = "logging.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_buckets: gapic_v1.method.wrap_method( + self.list_buckets, + default_timeout=None, + client_info=client_info, + ), + self.get_bucket: gapic_v1.method.wrap_method( + self.get_bucket, + default_timeout=None, + client_info=client_info, + ), + self.create_bucket_async: gapic_v1.method.wrap_method( + self.create_bucket_async, + default_timeout=None, + client_info=client_info, + ), + self.update_bucket_async: gapic_v1.method.wrap_method( + self.update_bucket_async, + default_timeout=None, + client_info=client_info, + ), + self.create_bucket: gapic_v1.method.wrap_method( + self.create_bucket, + default_timeout=None, + client_info=client_info, + ), + self.update_bucket: gapic_v1.method.wrap_method( + self.update_bucket, + default_timeout=None, + client_info=client_info, + ), + self.delete_bucket: gapic_v1.method.wrap_method( + self.delete_bucket, + default_timeout=None, + client_info=client_info, + ), + self.undelete_bucket: gapic_v1.method.wrap_method( + self.undelete_bucket, + default_timeout=None, + client_info=client_info, + ), + self.list_views: gapic_v1.method.wrap_method( + self.list_views, + default_timeout=None, + client_info=client_info, + ), + self.get_view: gapic_v1.method.wrap_method( + self.get_view, + default_timeout=None, + client_info=client_info, + ), + self.create_view: gapic_v1.method.wrap_method( + self.create_view, + default_timeout=None, + client_info=client_info, + ), + self.update_view: gapic_v1.method.wrap_method( + self.update_view, + default_timeout=None, + client_info=client_info, + ), + self.delete_view: gapic_v1.method.wrap_method( + self.delete_view, + default_timeout=None, + client_info=client_info, + ), + self.list_sinks: gapic_v1.method.wrap_method( + self.list_sinks, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_sink: gapic_v1.method.wrap_method( + self.get_sink, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_sink: gapic_v1.method.wrap_method( + self.create_sink, + default_timeout=120.0, + client_info=client_info, + ), + self.update_sink: gapic_v1.method.wrap_method( + self.update_sink, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_sink: gapic_v1.method.wrap_method( + self.delete_sink, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_link: gapic_v1.method.wrap_method( + self.create_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_link: gapic_v1.method.wrap_method( + self.delete_link, + default_timeout=None, + client_info=client_info, + ), + self.list_links: gapic_v1.method.wrap_method( + self.list_links, + default_timeout=None, + client_info=client_info, + ), + self.get_link: gapic_v1.method.wrap_method( + self.get_link, + default_timeout=None, + client_info=client_info, + ), + self.list_exclusions: gapic_v1.method.wrap_method( + self.list_exclusions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_exclusion: gapic_v1.method.wrap_method( + self.get_exclusion, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_exclusion: gapic_v1.method.wrap_method( + self.create_exclusion, + default_timeout=120.0, + client_info=client_info, + ), + self.update_exclusion: gapic_v1.method.wrap_method( + self.update_exclusion, + default_timeout=120.0, + client_info=client_info, + ), + self.delete_exclusion: gapic_v1.method.wrap_method( + self.delete_exclusion, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_cmek_settings: gapic_v1.method.wrap_method( + self.get_cmek_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_cmek_settings: gapic_v1.method.wrap_method( + self.update_cmek_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_settings: gapic_v1.method.wrap_method( + self.get_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_settings: gapic_v1.method.wrap_method( + self.update_settings, + default_timeout=None, + client_info=client_info, + ), + self.copy_log_entries: gapic_v1.method.wrap_method( + self.copy_log_entries, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_bucket( + self, + ) -> Callable[ + [logging_config.GetBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: + raise NotImplementedError() + + @property + def create_bucket_async( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_bucket_async( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_bucket( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: + raise NotImplementedError() + + @property + def update_bucket( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: + raise NotImplementedError() + + @property + def delete_bucket( + self, + ) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def undelete_bucket( + self, + ) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_views( + self, + ) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_view( + self, + ) -> Callable[ + [logging_config.GetViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: + raise NotImplementedError() + + @property + def create_view( + self, + ) -> Callable[ + [logging_config.CreateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: + raise NotImplementedError() + + @property + def update_view( + self, + ) -> Callable[ + [logging_config.UpdateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: + raise NotImplementedError() + + @property + def delete_view( + self, + ) -> Callable[ + [logging_config.DeleteViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_sinks( + self, + ) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_sink( + self, + ) -> Callable[ + [logging_config.GetSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: + raise NotImplementedError() + + @property + def create_sink( + self, + ) -> Callable[ + [logging_config.CreateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: + raise NotImplementedError() + + @property + def update_sink( + self, + ) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: + raise NotImplementedError() + + @property + def delete_sink( + self, + ) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_link( + self, + ) -> Callable[ + [logging_config.CreateLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_link( + self, + ) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_links( + self, + ) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_link( + self, + ) -> Callable[ + [logging_config.GetLinkRequest], + Union[logging_config.Link, Awaitable[logging_config.Link]], + ]: + raise NotImplementedError() + + @property + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_exclusion( + self, + ) -> Callable[ + [logging_config.GetExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: + raise NotImplementedError() + + @property + def create_exclusion( + self, + ) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: + raise NotImplementedError() + + @property + def update_exclusion( + self, + ) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: + raise NotImplementedError() + + @property + def delete_exclusion( + self, + ) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_cmek_settings( + self, + ) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: + raise NotImplementedError() + + @property + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: + raise NotImplementedError() + + @property + def get_settings( + self, + ) -> Callable[ + [logging_config.GetSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: + raise NotImplementedError() + + @property + def update_settings( + self, + ) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: + raise NotImplementedError() + + @property + def copy_log_entries( + self, + ) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ConfigServiceV2Transport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..a484749fcd8afc2273eabb546b04f57fad0ce927 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -0,0 +1,1347 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.logging_v2.types import logging_config + +from .base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.logging.v2.ConfigServiceV2", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.logging.v2.ConfigServiceV2", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ConfigServiceV2GrpcTransport(ConfigServiceV2Transport): + """gRPC backend transport for ConfigServiceV2. + + Service for configuring sinks used to route log entries. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], logging_config.ListBucketsResponse + ]: + r"""Return a callable for the list buckets method over gRPC. + + Lists log buckets. + + Returns: + Callable[[~.ListBucketsRequest], + ~.ListBucketsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_buckets" not in self._stubs: + self._stubs["list_buckets"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListBuckets", + request_serializer=logging_config.ListBucketsRequest.serialize, + response_deserializer=logging_config.ListBucketsResponse.deserialize, + ) + return self._stubs["list_buckets"] + + @property + def get_bucket( + self, + ) -> Callable[[logging_config.GetBucketRequest], logging_config.LogBucket]: + r"""Return a callable for the get bucket method over gRPC. + + Gets a log bucket. + + Returns: + Callable[[~.GetBucketRequest], + ~.LogBucket]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_bucket" not in self._stubs: + self._stubs["get_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetBucket", + request_serializer=logging_config.GetBucketRequest.serialize, + response_deserializer=logging_config.LogBucket.deserialize, + ) + return self._stubs["get_bucket"] + + @property + def create_bucket_async( + self, + ) -> Callable[[logging_config.CreateBucketRequest], operations_pb2.Operation]: + r"""Return a callable for the create bucket async method over gRPC. + + Creates a log bucket asynchronously that can be used + to store log entries. + After a bucket has been created, the bucket's location + cannot be changed. + + Returns: + Callable[[~.CreateBucketRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_bucket_async" not in self._stubs: + self._stubs["create_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucketAsync", + request_serializer=logging_config.CreateBucketRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_bucket_async"] + + @property + def update_bucket_async( + self, + ) -> Callable[[logging_config.UpdateBucketRequest], operations_pb2.Operation]: + r"""Return a callable for the update bucket async method over gRPC. + + Updates a log bucket asynchronously. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + Returns: + Callable[[~.UpdateBucketRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_bucket_async" not in self._stubs: + self._stubs["update_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucketAsync", + request_serializer=logging_config.UpdateBucketRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_bucket_async"] + + @property + def create_bucket( + self, + ) -> Callable[[logging_config.CreateBucketRequest], logging_config.LogBucket]: + r"""Return a callable for the create bucket method over gRPC. + + Creates a log bucket that can be used to store log + entries. After a bucket has been created, the bucket's + location cannot be changed. + + Returns: + Callable[[~.CreateBucketRequest], + ~.LogBucket]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_bucket" not in self._stubs: + self._stubs["create_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucket", + request_serializer=logging_config.CreateBucketRequest.serialize, + response_deserializer=logging_config.LogBucket.deserialize, + ) + return self._stubs["create_bucket"] + + @property + def update_bucket( + self, + ) -> Callable[[logging_config.UpdateBucketRequest], logging_config.LogBucket]: + r"""Return a callable for the update bucket method over gRPC. + + Updates a log bucket. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + Returns: + Callable[[~.UpdateBucketRequest], + ~.LogBucket]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_bucket" not in self._stubs: + self._stubs["update_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucket", + request_serializer=logging_config.UpdateBucketRequest.serialize, + response_deserializer=logging_config.LogBucket.deserialize, + ) + return self._stubs["update_bucket"] + + @property + def delete_bucket( + self, + ) -> Callable[[logging_config.DeleteBucketRequest], empty_pb2.Empty]: + r"""Return a callable for the delete bucket method over gRPC. + + Deletes a log bucket. + + Changes the bucket's ``lifecycle_state`` to the + ``DELETE_REQUESTED`` state. After 7 days, the bucket will be + purged and all log entries in the bucket will be permanently + deleted. + + Returns: + Callable[[~.DeleteBucketRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_bucket" not in self._stubs: + self._stubs["delete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteBucket", + request_serializer=logging_config.DeleteBucketRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_bucket"] + + @property + def undelete_bucket( + self, + ) -> Callable[[logging_config.UndeleteBucketRequest], empty_pb2.Empty]: + r"""Return a callable for the undelete bucket method over gRPC. + + Undeletes a log bucket. A bucket that has been + deleted can be undeleted within the grace period of 7 + days. + + Returns: + Callable[[~.UndeleteBucketRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_bucket" not in self._stubs: + self._stubs["undelete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UndeleteBucket", + request_serializer=logging_config.UndeleteBucketRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["undelete_bucket"] + + @property + def list_views( + self, + ) -> Callable[[logging_config.ListViewsRequest], logging_config.ListViewsResponse]: + r"""Return a callable for the list views method over gRPC. + + Lists views on a log bucket. + + Returns: + Callable[[~.ListViewsRequest], + ~.ListViewsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_views" not in self._stubs: + self._stubs["list_views"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListViews", + request_serializer=logging_config.ListViewsRequest.serialize, + response_deserializer=logging_config.ListViewsResponse.deserialize, + ) + return self._stubs["list_views"] + + @property + def get_view( + self, + ) -> Callable[[logging_config.GetViewRequest], logging_config.LogView]: + r"""Return a callable for the get view method over gRPC. + + Gets a view on a log bucket.. + + Returns: + Callable[[~.GetViewRequest], + ~.LogView]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_view" not in self._stubs: + self._stubs["get_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetView", + request_serializer=logging_config.GetViewRequest.serialize, + response_deserializer=logging_config.LogView.deserialize, + ) + return self._stubs["get_view"] + + @property + def create_view( + self, + ) -> Callable[[logging_config.CreateViewRequest], logging_config.LogView]: + r"""Return a callable for the create view method over gRPC. + + Creates a view over log entries in a log bucket. A + bucket may contain a maximum of 30 views. + + Returns: + Callable[[~.CreateViewRequest], + ~.LogView]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_view" not in self._stubs: + self._stubs["create_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateView", + request_serializer=logging_config.CreateViewRequest.serialize, + response_deserializer=logging_config.LogView.deserialize, + ) + return self._stubs["create_view"] + + @property + def update_view( + self, + ) -> Callable[[logging_config.UpdateViewRequest], logging_config.LogView]: + r"""Return a callable for the update view method over gRPC. + + Updates a view on a log bucket. This method replaces the + following fields in the existing view with values from the new + view: ``filter``. If an ``UNAVAILABLE`` error is returned, this + indicates that system is not in a state where it can update the + view. If this occurs, please try again in a few minutes. + + Returns: + Callable[[~.UpdateViewRequest], + ~.LogView]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_view" not in self._stubs: + self._stubs["update_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateView", + request_serializer=logging_config.UpdateViewRequest.serialize, + response_deserializer=logging_config.LogView.deserialize, + ) + return self._stubs["update_view"] + + @property + def delete_view( + self, + ) -> Callable[[logging_config.DeleteViewRequest], empty_pb2.Empty]: + r"""Return a callable for the delete view method over gRPC. + + Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is + returned, this indicates that system is not in a state where it + can delete the view. If this occurs, please try again in a few + minutes. + + Returns: + Callable[[~.DeleteViewRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_view" not in self._stubs: + self._stubs["delete_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteView", + request_serializer=logging_config.DeleteViewRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_view"] + + @property + def list_sinks( + self, + ) -> Callable[[logging_config.ListSinksRequest], logging_config.ListSinksResponse]: + r"""Return a callable for the list sinks method over gRPC. + + Lists sinks. + + Returns: + Callable[[~.ListSinksRequest], + ~.ListSinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_sinks" not in self._stubs: + self._stubs["list_sinks"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListSinks", + request_serializer=logging_config.ListSinksRequest.serialize, + response_deserializer=logging_config.ListSinksResponse.deserialize, + ) + return self._stubs["list_sinks"] + + @property + def get_sink( + self, + ) -> Callable[[logging_config.GetSinkRequest], logging_config.LogSink]: + r"""Return a callable for the get sink method over gRPC. + + Gets a sink. + + Returns: + Callable[[~.GetSinkRequest], + ~.LogSink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sink" not in self._stubs: + self._stubs["get_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSink", + request_serializer=logging_config.GetSinkRequest.serialize, + response_deserializer=logging_config.LogSink.deserialize, + ) + return self._stubs["get_sink"] + + @property + def create_sink( + self, + ) -> Callable[[logging_config.CreateSinkRequest], logging_config.LogSink]: + r"""Return a callable for the create sink method over gRPC. + + Creates a sink that exports specified log entries to a + destination. The export of newly-ingested log entries begins + immediately, unless the sink's ``writer_identity`` is not + permitted to write to the destination. A sink can export log + entries only from the resource owning the sink. + + Returns: + Callable[[~.CreateSinkRequest], + ~.LogSink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_sink" not in self._stubs: + self._stubs["create_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateSink", + request_serializer=logging_config.CreateSinkRequest.serialize, + response_deserializer=logging_config.LogSink.deserialize, + ) + return self._stubs["create_sink"] + + @property + def update_sink( + self, + ) -> Callable[[logging_config.UpdateSinkRequest], logging_config.LogSink]: + r"""Return a callable for the update sink method over gRPC. + + Updates a sink. This method replaces the following fields in the + existing sink with values from the new sink: ``destination``, + and ``filter``. + + The updated sink might also have a new ``writer_identity``; see + the ``unique_writer_identity`` field. + + Returns: + Callable[[~.UpdateSinkRequest], + ~.LogSink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_sink" not in self._stubs: + self._stubs["update_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSink", + request_serializer=logging_config.UpdateSinkRequest.serialize, + response_deserializer=logging_config.LogSink.deserialize, + ) + return self._stubs["update_sink"] + + @property + def delete_sink( + self, + ) -> Callable[[logging_config.DeleteSinkRequest], empty_pb2.Empty]: + r"""Return a callable for the delete sink method over gRPC. + + Deletes a sink. If the sink has a unique ``writer_identity``, + then that service account is also deleted. + + Returns: + Callable[[~.DeleteSinkRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sink" not in self._stubs: + self._stubs["delete_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteSink", + request_serializer=logging_config.DeleteSinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sink"] + + @property + def create_link( + self, + ) -> Callable[[logging_config.CreateLinkRequest], operations_pb2.Operation]: + r"""Return a callable for the create link method over gRPC. + + Asynchronously creates a linked dataset in BigQuery + which makes it possible to use BigQuery to read the logs + stored in the log bucket. A log bucket may currently + only contain one link. + + Returns: + Callable[[~.CreateLinkRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_link" not in self._stubs: + self._stubs["create_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateLink", + request_serializer=logging_config.CreateLinkRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_link"] + + @property + def delete_link( + self, + ) -> Callable[[logging_config.DeleteLinkRequest], operations_pb2.Operation]: + r"""Return a callable for the delete link method over gRPC. + + Deletes a link. This will also delete the + corresponding BigQuery linked dataset. + + Returns: + Callable[[~.DeleteLinkRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_link" not in self._stubs: + self._stubs["delete_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteLink", + request_serializer=logging_config.DeleteLinkRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_link"] + + @property + def list_links( + self, + ) -> Callable[[logging_config.ListLinksRequest], logging_config.ListLinksResponse]: + r"""Return a callable for the list links method over gRPC. + + Lists links. + + Returns: + Callable[[~.ListLinksRequest], + ~.ListLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_links" not in self._stubs: + self._stubs["list_links"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListLinks", + request_serializer=logging_config.ListLinksRequest.serialize, + response_deserializer=logging_config.ListLinksResponse.deserialize, + ) + return self._stubs["list_links"] + + @property + def get_link( + self, + ) -> Callable[[logging_config.GetLinkRequest], logging_config.Link]: + r"""Return a callable for the get link method over gRPC. + + Gets a link. + + Returns: + Callable[[~.GetLinkRequest], + ~.Link]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_link" not in self._stubs: + self._stubs["get_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetLink", + request_serializer=logging_config.GetLinkRequest.serialize, + response_deserializer=logging_config.Link.deserialize, + ) + return self._stubs["get_link"] + + @property + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], logging_config.ListExclusionsResponse + ]: + r"""Return a callable for the list exclusions method over gRPC. + + Lists all the exclusions on the \_Default sink in a parent + resource. + + Returns: + Callable[[~.ListExclusionsRequest], + ~.ListExclusionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_exclusions" not in self._stubs: + self._stubs["list_exclusions"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListExclusions", + request_serializer=logging_config.ListExclusionsRequest.serialize, + response_deserializer=logging_config.ListExclusionsResponse.deserialize, + ) + return self._stubs["list_exclusions"] + + @property + def get_exclusion( + self, + ) -> Callable[[logging_config.GetExclusionRequest], logging_config.LogExclusion]: + r"""Return a callable for the get exclusion method over gRPC. + + Gets the description of an exclusion in the \_Default sink. + + Returns: + Callable[[~.GetExclusionRequest], + ~.LogExclusion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_exclusion" not in self._stubs: + self._stubs["get_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetExclusion", + request_serializer=logging_config.GetExclusionRequest.serialize, + response_deserializer=logging_config.LogExclusion.deserialize, + ) + return self._stubs["get_exclusion"] + + @property + def create_exclusion( + self, + ) -> Callable[[logging_config.CreateExclusionRequest], logging_config.LogExclusion]: + r"""Return a callable for the create exclusion method over gRPC. + + Creates a new exclusion in the \_Default sink in a specified + parent resource. Only log entries belonging to that resource can + be excluded. You can have up to 10 exclusions in a resource. + + Returns: + Callable[[~.CreateExclusionRequest], + ~.LogExclusion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_exclusion" not in self._stubs: + self._stubs["create_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateExclusion", + request_serializer=logging_config.CreateExclusionRequest.serialize, + response_deserializer=logging_config.LogExclusion.deserialize, + ) + return self._stubs["create_exclusion"] + + @property + def update_exclusion( + self, + ) -> Callable[[logging_config.UpdateExclusionRequest], logging_config.LogExclusion]: + r"""Return a callable for the update exclusion method over gRPC. + + Changes one or more properties of an existing exclusion in the + \_Default sink. + + Returns: + Callable[[~.UpdateExclusionRequest], + ~.LogExclusion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_exclusion" not in self._stubs: + self._stubs["update_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateExclusion", + request_serializer=logging_config.UpdateExclusionRequest.serialize, + response_deserializer=logging_config.LogExclusion.deserialize, + ) + return self._stubs["update_exclusion"] + + @property + def delete_exclusion( + self, + ) -> Callable[[logging_config.DeleteExclusionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete exclusion method over gRPC. + + Deletes an exclusion in the \_Default sink. + + Returns: + Callable[[~.DeleteExclusionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_exclusion" not in self._stubs: + self._stubs["delete_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteExclusion", + request_serializer=logging_config.DeleteExclusionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_exclusion"] + + @property + def get_cmek_settings( + self, + ) -> Callable[[logging_config.GetCmekSettingsRequest], logging_config.CmekSettings]: + r"""Return a callable for the get cmek settings method over gRPC. + + Gets the Logging CMEK settings for the given resource. + + Note: CMEK for the Log Router can be configured for Google Cloud + projects, folders, organizations and billing accounts. Once + configured for an organization, it applies to all projects and + folders in the Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.GetCmekSettingsRequest], + ~.CmekSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_cmek_settings" not in self._stubs: + self._stubs["get_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetCmekSettings", + request_serializer=logging_config.GetCmekSettingsRequest.serialize, + response_deserializer=logging_config.CmekSettings.deserialize, + ) + return self._stubs["get_cmek_settings"] + + @property + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], logging_config.CmekSettings + ]: + r"""Return a callable for the update cmek settings method over gRPC. + + Updates the Log Router CMEK settings for the given resource. + + Note: CMEK for the Log Router can currently only be configured + for Google Cloud organizations. Once configured, it applies to + all projects and folders in the Google Cloud organization. + + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.UpdateCmekSettingsRequest], + ~.CmekSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_cmek_settings" not in self._stubs: + self._stubs["update_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateCmekSettings", + request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, + response_deserializer=logging_config.CmekSettings.deserialize, + ) + return self._stubs["update_cmek_settings"] + + @property + def get_settings( + self, + ) -> Callable[[logging_config.GetSettingsRequest], logging_config.Settings]: + r"""Return a callable for the get settings method over gRPC. + + Gets the Log Router settings for the given resource. + + Note: Settings for the Log Router can be get for Google Cloud + projects, folders, organizations and billing accounts. Currently + it can only be configured for organizations. Once configured for + an organization, it applies to all projects and folders in the + Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.GetSettingsRequest], + ~.Settings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_settings" not in self._stubs: + self._stubs["get_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSettings", + request_serializer=logging_config.GetSettingsRequest.serialize, + response_deserializer=logging_config.Settings.deserialize, + ) + return self._stubs["get_settings"] + + @property + def update_settings( + self, + ) -> Callable[[logging_config.UpdateSettingsRequest], logging_config.Settings]: + r"""Return a callable for the update settings method over gRPC. + + Updates the Log Router settings for the given resource. + + Note: Settings for the Log Router can currently only be + configured for Google Cloud organizations. Once configured, it + applies to all projects and folders in the Google Cloud + organization. + + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. 4) ``location_id`` + is not supported by Logging. 5) ``location_id`` violate + OrgPolicy. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.UpdateSettingsRequest], + ~.Settings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_settings" not in self._stubs: + self._stubs["update_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSettings", + request_serializer=logging_config.UpdateSettingsRequest.serialize, + response_deserializer=logging_config.Settings.deserialize, + ) + return self._stubs["update_settings"] + + @property + def copy_log_entries( + self, + ) -> Callable[[logging_config.CopyLogEntriesRequest], operations_pb2.Operation]: + r"""Return a callable for the copy log entries method over gRPC. + + Copies a set of log entries from a log bucket to a + Cloud Storage bucket. + + Returns: + Callable[[~.CopyLogEntriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "copy_log_entries" not in self._stubs: + self._stubs["copy_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CopyLogEntries", + request_serializer=logging_config.CopyLogEntriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["copy_log_entries"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("ConfigServiceV2GrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1ca1e1f45c09760a8a26a7084b9907392a0c3c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py @@ -0,0 +1,1662 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.logging_v2.types import logging_config + +from .base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from .grpc import ConfigServiceV2GrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.logging.v2.ConfigServiceV2", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.logging.v2.ConfigServiceV2", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ConfigServiceV2GrpcAsyncIOTransport(ConfigServiceV2Transport): + """gRPC AsyncIO backend transport for ConfigServiceV2. + + Service for configuring sinks used to route log entries. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], + Awaitable[logging_config.ListBucketsResponse], + ]: + r"""Return a callable for the list buckets method over gRPC. + + Lists log buckets. + + Returns: + Callable[[~.ListBucketsRequest], + Awaitable[~.ListBucketsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_buckets" not in self._stubs: + self._stubs["list_buckets"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListBuckets", + request_serializer=logging_config.ListBucketsRequest.serialize, + response_deserializer=logging_config.ListBucketsResponse.deserialize, + ) + return self._stubs["list_buckets"] + + @property + def get_bucket( + self, + ) -> Callable[ + [logging_config.GetBucketRequest], Awaitable[logging_config.LogBucket] + ]: + r"""Return a callable for the get bucket method over gRPC. + + Gets a log bucket. + + Returns: + Callable[[~.GetBucketRequest], + Awaitable[~.LogBucket]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_bucket" not in self._stubs: + self._stubs["get_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetBucket", + request_serializer=logging_config.GetBucketRequest.serialize, + response_deserializer=logging_config.LogBucket.deserialize, + ) + return self._stubs["get_bucket"] + + @property + def create_bucket_async( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create bucket async method over gRPC. + + Creates a log bucket asynchronously that can be used + to store log entries. + After a bucket has been created, the bucket's location + cannot be changed. + + Returns: + Callable[[~.CreateBucketRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_bucket_async" not in self._stubs: + self._stubs["create_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucketAsync", + request_serializer=logging_config.CreateBucketRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_bucket_async"] + + @property + def update_bucket_async( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update bucket async method over gRPC. + + Updates a log bucket asynchronously. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + Returns: + Callable[[~.UpdateBucketRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_bucket_async" not in self._stubs: + self._stubs["update_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucketAsync", + request_serializer=logging_config.UpdateBucketRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_bucket_async"] + + @property + def create_bucket( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], Awaitable[logging_config.LogBucket] + ]: + r"""Return a callable for the create bucket method over gRPC. + + Creates a log bucket that can be used to store log + entries. After a bucket has been created, the bucket's + location cannot be changed. + + Returns: + Callable[[~.CreateBucketRequest], + Awaitable[~.LogBucket]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_bucket" not in self._stubs: + self._stubs["create_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucket", + request_serializer=logging_config.CreateBucketRequest.serialize, + response_deserializer=logging_config.LogBucket.deserialize, + ) + return self._stubs["create_bucket"] + + @property + def update_bucket( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], Awaitable[logging_config.LogBucket] + ]: + r"""Return a callable for the update bucket method over gRPC. + + Updates a log bucket. + + If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, + then ``FAILED_PRECONDITION`` will be returned. + + After a bucket has been created, the bucket's location cannot be + changed. + + Returns: + Callable[[~.UpdateBucketRequest], + Awaitable[~.LogBucket]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_bucket" not in self._stubs: + self._stubs["update_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucket", + request_serializer=logging_config.UpdateBucketRequest.serialize, + response_deserializer=logging_config.LogBucket.deserialize, + ) + return self._stubs["update_bucket"] + + @property + def delete_bucket( + self, + ) -> Callable[[logging_config.DeleteBucketRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete bucket method over gRPC. + + Deletes a log bucket. + + Changes the bucket's ``lifecycle_state`` to the + ``DELETE_REQUESTED`` state. After 7 days, the bucket will be + purged and all log entries in the bucket will be permanently + deleted. + + Returns: + Callable[[~.DeleteBucketRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_bucket" not in self._stubs: + self._stubs["delete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteBucket", + request_serializer=logging_config.DeleteBucketRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_bucket"] + + @property + def undelete_bucket( + self, + ) -> Callable[[logging_config.UndeleteBucketRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the undelete bucket method over gRPC. + + Undeletes a log bucket. A bucket that has been + deleted can be undeleted within the grace period of 7 + days. + + Returns: + Callable[[~.UndeleteBucketRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_bucket" not in self._stubs: + self._stubs["undelete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UndeleteBucket", + request_serializer=logging_config.UndeleteBucketRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["undelete_bucket"] + + @property + def list_views( + self, + ) -> Callable[ + [logging_config.ListViewsRequest], Awaitable[logging_config.ListViewsResponse] + ]: + r"""Return a callable for the list views method over gRPC. + + Lists views on a log bucket. + + Returns: + Callable[[~.ListViewsRequest], + Awaitable[~.ListViewsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_views" not in self._stubs: + self._stubs["list_views"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListViews", + request_serializer=logging_config.ListViewsRequest.serialize, + response_deserializer=logging_config.ListViewsResponse.deserialize, + ) + return self._stubs["list_views"] + + @property + def get_view( + self, + ) -> Callable[[logging_config.GetViewRequest], Awaitable[logging_config.LogView]]: + r"""Return a callable for the get view method over gRPC. + + Gets a view on a log bucket.. + + Returns: + Callable[[~.GetViewRequest], + Awaitable[~.LogView]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_view" not in self._stubs: + self._stubs["get_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetView", + request_serializer=logging_config.GetViewRequest.serialize, + response_deserializer=logging_config.LogView.deserialize, + ) + return self._stubs["get_view"] + + @property + def create_view( + self, + ) -> Callable[ + [logging_config.CreateViewRequest], Awaitable[logging_config.LogView] + ]: + r"""Return a callable for the create view method over gRPC. + + Creates a view over log entries in a log bucket. A + bucket may contain a maximum of 30 views. + + Returns: + Callable[[~.CreateViewRequest], + Awaitable[~.LogView]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_view" not in self._stubs: + self._stubs["create_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateView", + request_serializer=logging_config.CreateViewRequest.serialize, + response_deserializer=logging_config.LogView.deserialize, + ) + return self._stubs["create_view"] + + @property + def update_view( + self, + ) -> Callable[ + [logging_config.UpdateViewRequest], Awaitable[logging_config.LogView] + ]: + r"""Return a callable for the update view method over gRPC. + + Updates a view on a log bucket. This method replaces the + following fields in the existing view with values from the new + view: ``filter``. If an ``UNAVAILABLE`` error is returned, this + indicates that system is not in a state where it can update the + view. If this occurs, please try again in a few minutes. + + Returns: + Callable[[~.UpdateViewRequest], + Awaitable[~.LogView]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_view" not in self._stubs: + self._stubs["update_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateView", + request_serializer=logging_config.UpdateViewRequest.serialize, + response_deserializer=logging_config.LogView.deserialize, + ) + return self._stubs["update_view"] + + @property + def delete_view( + self, + ) -> Callable[[logging_config.DeleteViewRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete view method over gRPC. + + Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is + returned, this indicates that system is not in a state where it + can delete the view. If this occurs, please try again in a few + minutes. + + Returns: + Callable[[~.DeleteViewRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_view" not in self._stubs: + self._stubs["delete_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteView", + request_serializer=logging_config.DeleteViewRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_view"] + + @property + def list_sinks( + self, + ) -> Callable[ + [logging_config.ListSinksRequest], Awaitable[logging_config.ListSinksResponse] + ]: + r"""Return a callable for the list sinks method over gRPC. + + Lists sinks. + + Returns: + Callable[[~.ListSinksRequest], + Awaitable[~.ListSinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_sinks" not in self._stubs: + self._stubs["list_sinks"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListSinks", + request_serializer=logging_config.ListSinksRequest.serialize, + response_deserializer=logging_config.ListSinksResponse.deserialize, + ) + return self._stubs["list_sinks"] + + @property + def get_sink( + self, + ) -> Callable[[logging_config.GetSinkRequest], Awaitable[logging_config.LogSink]]: + r"""Return a callable for the get sink method over gRPC. + + Gets a sink. + + Returns: + Callable[[~.GetSinkRequest], + Awaitable[~.LogSink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sink" not in self._stubs: + self._stubs["get_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSink", + request_serializer=logging_config.GetSinkRequest.serialize, + response_deserializer=logging_config.LogSink.deserialize, + ) + return self._stubs["get_sink"] + + @property + def create_sink( + self, + ) -> Callable[ + [logging_config.CreateSinkRequest], Awaitable[logging_config.LogSink] + ]: + r"""Return a callable for the create sink method over gRPC. + + Creates a sink that exports specified log entries to a + destination. The export of newly-ingested log entries begins + immediately, unless the sink's ``writer_identity`` is not + permitted to write to the destination. A sink can export log + entries only from the resource owning the sink. + + Returns: + Callable[[~.CreateSinkRequest], + Awaitable[~.LogSink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_sink" not in self._stubs: + self._stubs["create_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateSink", + request_serializer=logging_config.CreateSinkRequest.serialize, + response_deserializer=logging_config.LogSink.deserialize, + ) + return self._stubs["create_sink"] + + @property + def update_sink( + self, + ) -> Callable[ + [logging_config.UpdateSinkRequest], Awaitable[logging_config.LogSink] + ]: + r"""Return a callable for the update sink method over gRPC. + + Updates a sink. This method replaces the following fields in the + existing sink with values from the new sink: ``destination``, + and ``filter``. + + The updated sink might also have a new ``writer_identity``; see + the ``unique_writer_identity`` field. + + Returns: + Callable[[~.UpdateSinkRequest], + Awaitable[~.LogSink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_sink" not in self._stubs: + self._stubs["update_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSink", + request_serializer=logging_config.UpdateSinkRequest.serialize, + response_deserializer=logging_config.LogSink.deserialize, + ) + return self._stubs["update_sink"] + + @property + def delete_sink( + self, + ) -> Callable[[logging_config.DeleteSinkRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete sink method over gRPC. + + Deletes a sink. If the sink has a unique ``writer_identity``, + then that service account is also deleted. + + Returns: + Callable[[~.DeleteSinkRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sink" not in self._stubs: + self._stubs["delete_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteSink", + request_serializer=logging_config.DeleteSinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sink"] + + @property + def create_link( + self, + ) -> Callable[ + [logging_config.CreateLinkRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create link method over gRPC. + + Asynchronously creates a linked dataset in BigQuery + which makes it possible to use BigQuery to read the logs + stored in the log bucket. A log bucket may currently + only contain one link. + + Returns: + Callable[[~.CreateLinkRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_link" not in self._stubs: + self._stubs["create_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateLink", + request_serializer=logging_config.CreateLinkRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_link"] + + @property + def delete_link( + self, + ) -> Callable[ + [logging_config.DeleteLinkRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete link method over gRPC. + + Deletes a link. This will also delete the + corresponding BigQuery linked dataset. + + Returns: + Callable[[~.DeleteLinkRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_link" not in self._stubs: + self._stubs["delete_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteLink", + request_serializer=logging_config.DeleteLinkRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_link"] + + @property + def list_links( + self, + ) -> Callable[ + [logging_config.ListLinksRequest], Awaitable[logging_config.ListLinksResponse] + ]: + r"""Return a callable for the list links method over gRPC. + + Lists links. + + Returns: + Callable[[~.ListLinksRequest], + Awaitable[~.ListLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_links" not in self._stubs: + self._stubs["list_links"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListLinks", + request_serializer=logging_config.ListLinksRequest.serialize, + response_deserializer=logging_config.ListLinksResponse.deserialize, + ) + return self._stubs["list_links"] + + @property + def get_link( + self, + ) -> Callable[[logging_config.GetLinkRequest], Awaitable[logging_config.Link]]: + r"""Return a callable for the get link method over gRPC. + + Gets a link. + + Returns: + Callable[[~.GetLinkRequest], + Awaitable[~.Link]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_link" not in self._stubs: + self._stubs["get_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetLink", + request_serializer=logging_config.GetLinkRequest.serialize, + response_deserializer=logging_config.Link.deserialize, + ) + return self._stubs["get_link"] + + @property + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], + Awaitable[logging_config.ListExclusionsResponse], + ]: + r"""Return a callable for the list exclusions method over gRPC. + + Lists all the exclusions on the \_Default sink in a parent + resource. + + Returns: + Callable[[~.ListExclusionsRequest], + Awaitable[~.ListExclusionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_exclusions" not in self._stubs: + self._stubs["list_exclusions"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListExclusions", + request_serializer=logging_config.ListExclusionsRequest.serialize, + response_deserializer=logging_config.ListExclusionsResponse.deserialize, + ) + return self._stubs["list_exclusions"] + + @property + def get_exclusion( + self, + ) -> Callable[ + [logging_config.GetExclusionRequest], Awaitable[logging_config.LogExclusion] + ]: + r"""Return a callable for the get exclusion method over gRPC. + + Gets the description of an exclusion in the \_Default sink. + + Returns: + Callable[[~.GetExclusionRequest], + Awaitable[~.LogExclusion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_exclusion" not in self._stubs: + self._stubs["get_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetExclusion", + request_serializer=logging_config.GetExclusionRequest.serialize, + response_deserializer=logging_config.LogExclusion.deserialize, + ) + return self._stubs["get_exclusion"] + + @property + def create_exclusion( + self, + ) -> Callable[ + [logging_config.CreateExclusionRequest], Awaitable[logging_config.LogExclusion] + ]: + r"""Return a callable for the create exclusion method over gRPC. + + Creates a new exclusion in the \_Default sink in a specified + parent resource. Only log entries belonging to that resource can + be excluded. You can have up to 10 exclusions in a resource. + + Returns: + Callable[[~.CreateExclusionRequest], + Awaitable[~.LogExclusion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_exclusion" not in self._stubs: + self._stubs["create_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateExclusion", + request_serializer=logging_config.CreateExclusionRequest.serialize, + response_deserializer=logging_config.LogExclusion.deserialize, + ) + return self._stubs["create_exclusion"] + + @property + def update_exclusion( + self, + ) -> Callable[ + [logging_config.UpdateExclusionRequest], Awaitable[logging_config.LogExclusion] + ]: + r"""Return a callable for the update exclusion method over gRPC. + + Changes one or more properties of an existing exclusion in the + \_Default sink. + + Returns: + Callable[[~.UpdateExclusionRequest], + Awaitable[~.LogExclusion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_exclusion" not in self._stubs: + self._stubs["update_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateExclusion", + request_serializer=logging_config.UpdateExclusionRequest.serialize, + response_deserializer=logging_config.LogExclusion.deserialize, + ) + return self._stubs["update_exclusion"] + + @property + def delete_exclusion( + self, + ) -> Callable[[logging_config.DeleteExclusionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete exclusion method over gRPC. + + Deletes an exclusion in the \_Default sink. + + Returns: + Callable[[~.DeleteExclusionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_exclusion" not in self._stubs: + self._stubs["delete_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteExclusion", + request_serializer=logging_config.DeleteExclusionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_exclusion"] + + @property + def get_cmek_settings( + self, + ) -> Callable[ + [logging_config.GetCmekSettingsRequest], Awaitable[logging_config.CmekSettings] + ]: + r"""Return a callable for the get cmek settings method over gRPC. + + Gets the Logging CMEK settings for the given resource. + + Note: CMEK for the Log Router can be configured for Google Cloud + projects, folders, organizations and billing accounts. Once + configured for an organization, it applies to all projects and + folders in the Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.GetCmekSettingsRequest], + Awaitable[~.CmekSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_cmek_settings" not in self._stubs: + self._stubs["get_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetCmekSettings", + request_serializer=logging_config.GetCmekSettingsRequest.serialize, + response_deserializer=logging_config.CmekSettings.deserialize, + ) + return self._stubs["get_cmek_settings"] + + @property + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Awaitable[logging_config.CmekSettings], + ]: + r"""Return a callable for the update cmek settings method over gRPC. + + Updates the Log Router CMEK settings for the given resource. + + Note: CMEK for the Log Router can currently only be configured + for Google Cloud organizations. Once configured, it applies to + all projects and folders in the Google Cloud organization. + + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.UpdateCmekSettingsRequest], + Awaitable[~.CmekSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_cmek_settings" not in self._stubs: + self._stubs["update_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateCmekSettings", + request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, + response_deserializer=logging_config.CmekSettings.deserialize, + ) + return self._stubs["update_cmek_settings"] + + @property + def get_settings( + self, + ) -> Callable[ + [logging_config.GetSettingsRequest], Awaitable[logging_config.Settings] + ]: + r"""Return a callable for the get settings method over gRPC. + + Gets the Log Router settings for the given resource. + + Note: Settings for the Log Router can be get for Google Cloud + projects, folders, organizations and billing accounts. Currently + it can only be configured for organizations. Once configured for + an organization, it applies to all projects and folders in the + Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.GetSettingsRequest], + Awaitable[~.Settings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_settings" not in self._stubs: + self._stubs["get_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSettings", + request_serializer=logging_config.GetSettingsRequest.serialize, + response_deserializer=logging_config.Settings.deserialize, + ) + return self._stubs["get_settings"] + + @property + def update_settings( + self, + ) -> Callable[ + [logging_config.UpdateSettingsRequest], Awaitable[logging_config.Settings] + ]: + r"""Return a callable for the update settings method over gRPC. + + Updates the Log Router settings for the given resource. + + Note: Settings for the Log Router can currently only be + configured for Google Cloud organizations. Once configured, it + applies to all projects and folders in the Google Cloud + organization. + + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings] + will fail if 1) ``kms_key_name`` is invalid, or 2) the + associated service account does not have the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for + the key, or 3) access to the key is disabled. 4) ``location_id`` + is not supported by Logging. 5) ``location_id`` violate + OrgPolicy. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Returns: + Callable[[~.UpdateSettingsRequest], + Awaitable[~.Settings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_settings" not in self._stubs: + self._stubs["update_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSettings", + request_serializer=logging_config.UpdateSettingsRequest.serialize, + response_deserializer=logging_config.Settings.deserialize, + ) + return self._stubs["update_settings"] + + @property + def copy_log_entries( + self, + ) -> Callable[ + [logging_config.CopyLogEntriesRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the copy log entries method over gRPC. + + Copies a set of log entries from a log bucket to a + Cloud Storage bucket. + + Returns: + Callable[[~.CopyLogEntriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "copy_log_entries" not in self._stubs: + self._stubs["copy_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CopyLogEntries", + request_serializer=logging_config.CopyLogEntriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["copy_log_entries"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_buckets: self._wrap_method( + self.list_buckets, + default_timeout=None, + client_info=client_info, + ), + self.get_bucket: self._wrap_method( + self.get_bucket, + default_timeout=None, + client_info=client_info, + ), + self.create_bucket_async: self._wrap_method( + self.create_bucket_async, + default_timeout=None, + client_info=client_info, + ), + self.update_bucket_async: self._wrap_method( + self.update_bucket_async, + default_timeout=None, + client_info=client_info, + ), + self.create_bucket: self._wrap_method( + self.create_bucket, + default_timeout=None, + client_info=client_info, + ), + self.update_bucket: self._wrap_method( + self.update_bucket, + default_timeout=None, + client_info=client_info, + ), + self.delete_bucket: self._wrap_method( + self.delete_bucket, + default_timeout=None, + client_info=client_info, + ), + self.undelete_bucket: self._wrap_method( + self.undelete_bucket, + default_timeout=None, + client_info=client_info, + ), + self.list_views: self._wrap_method( + self.list_views, + default_timeout=None, + client_info=client_info, + ), + self.get_view: self._wrap_method( + self.get_view, + default_timeout=None, + client_info=client_info, + ), + self.create_view: self._wrap_method( + self.create_view, + default_timeout=None, + client_info=client_info, + ), + self.update_view: self._wrap_method( + self.update_view, + default_timeout=None, + client_info=client_info, + ), + self.delete_view: self._wrap_method( + self.delete_view, + default_timeout=None, + client_info=client_info, + ), + self.list_sinks: self._wrap_method( + self.list_sinks, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_sink: self._wrap_method( + self.get_sink, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_sink: self._wrap_method( + self.create_sink, + default_timeout=120.0, + client_info=client_info, + ), + self.update_sink: self._wrap_method( + self.update_sink, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_sink: self._wrap_method( + self.delete_sink, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_link: self._wrap_method( + self.create_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_link: self._wrap_method( + self.delete_link, + default_timeout=None, + client_info=client_info, + ), + self.list_links: self._wrap_method( + self.list_links, + default_timeout=None, + client_info=client_info, + ), + self.get_link: self._wrap_method( + self.get_link, + default_timeout=None, + client_info=client_info, + ), + self.list_exclusions: self._wrap_method( + self.list_exclusions, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_exclusion: self._wrap_method( + self.get_exclusion, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_exclusion: self._wrap_method( + self.create_exclusion, + default_timeout=120.0, + client_info=client_info, + ), + self.update_exclusion: self._wrap_method( + self.update_exclusion, + default_timeout=120.0, + client_info=client_info, + ), + self.delete_exclusion: self._wrap_method( + self.delete_exclusion, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_cmek_settings: self._wrap_method( + self.get_cmek_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_cmek_settings: self._wrap_method( + self.update_cmek_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_settings: self._wrap_method( + self.get_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_settings: self._wrap_method( + self.update_settings, + default_timeout=None, + client_info=client_info, + ), + self.copy_log_entries: self._wrap_method( + self.copy_log_entries, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("ConfigServiceV2GrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf59c378463ce94f28d0e8302d923029a9ba6c5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import LoggingServiceV2AsyncClient +from .client import LoggingServiceV2Client + +__all__ = ( + "LoggingServiceV2Client", + "LoggingServiceV2AsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..4b59013dbf041b30e2eca307dbee7730a3cf56e4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/async_client.py @@ -0,0 +1,1290 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +import uuid +from collections import OrderedDict +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.logging_v2.services.logging_service_v2 import pagers +from google.cloud.logging_v2.types import log_entry, logging + +from .client import LoggingServiceV2Client +from .transports.base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class LoggingServiceV2AsyncClient: + """Service for ingesting and querying logs.""" + + _client: LoggingServiceV2Client + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LoggingServiceV2Client.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LoggingServiceV2Client._DEFAULT_UNIVERSE + + log_path = staticmethod(LoggingServiceV2Client.log_path) + parse_log_path = staticmethod(LoggingServiceV2Client.parse_log_path) + common_billing_account_path = staticmethod( + LoggingServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LoggingServiceV2Client.parse_common_billing_account_path + ) + common_folder_path = staticmethod(LoggingServiceV2Client.common_folder_path) + parse_common_folder_path = staticmethod( + LoggingServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + LoggingServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + LoggingServiceV2Client.parse_common_organization_path + ) + common_project_path = staticmethod(LoggingServiceV2Client.common_project_path) + parse_common_project_path = staticmethod( + LoggingServiceV2Client.parse_common_project_path + ) + common_location_path = staticmethod(LoggingServiceV2Client.common_location_path) + parse_common_location_path = staticmethod( + LoggingServiceV2Client.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LoggingServiceV2AsyncClient: The constructed client. + """ + sa_info_func = ( + LoggingServiceV2Client.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(LoggingServiceV2AsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LoggingServiceV2AsyncClient: The constructed client. + """ + sa_file_func = ( + LoggingServiceV2Client.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(LoggingServiceV2AsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LoggingServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LoggingServiceV2Transport: + """Returns the transport used by the client instance. + + Returns: + LoggingServiceV2Transport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = LoggingServiceV2Client.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the logging service v2 async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LoggingServiceV2Transport,Callable[..., LoggingServiceV2Transport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LoggingServiceV2Transport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = LoggingServiceV2Client( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.logging_v2.LoggingServiceV2AsyncClient`.", + extra={ + "serviceName": "google.logging.v2.LoggingServiceV2", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.logging.v2.LoggingServiceV2", + "credentialsType": None, + }, + ) + + async def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes all the log entries in a log for the \_Default Log + Bucket. The log reappears if it receives new entries. Log + entries written shortly before the delete operation might not be + deleted. Entries received after the delete operation with a + timestamp before the operation will be deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_log(): + # Create a client + client = logging_v2.LoggingServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteLogRequest( + log_name="log_name_value", + ) + + # Make the request + await client.delete_log(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]]): + The request object. The parameters to DeleteLog. + log_name (:class:`str`): + Required. The resource name of the log to delete: + + - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` + - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` + - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` + + ``[LOG_ID]`` must be URL-encoded. For example, + ``"projects/my-project-id/logs/syslog"``, + ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``. + + For more information about log names, see + [LogEntry][google.logging.v2.LogEntry]. + + This corresponds to the ``log_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [log_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.DeleteLogRequest): + request = logging.DeleteLogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if log_name is not None: + request.log_name = log_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_log + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: + r"""Writes log entries to Logging. This API method is the + only way to send log entries to Logging. This method is + used, directly or indirectly, by the Logging agent + (fluentd) and all logging libraries configured to use + Logging. A single request may contain log entries for a + maximum of 1000 different resources (projects, + organizations, billing accounts or folders) + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_write_log_entries(): + # Create a client + client = logging_v2.LoggingServiceV2AsyncClient() + + # Initialize request argument(s) + entries = logging_v2.LogEntry() + entries.log_name = "log_name_value" + + request = logging_v2.WriteLogEntriesRequest( + entries=entries, + ) + + # Make the request + response = await client.write_log_entries(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]]): + The request object. The parameters to WriteLogEntries. + log_name (:class:`str`): + Optional. A default log resource name that is assigned + to all log entries in ``entries`` that do not specify a + value for ``log_name``: + + - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` + - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` + - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` + + ``[LOG_ID]`` must be URL-encoded. For example: + + :: + + "projects/my-project-id/logs/syslog" + "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" + + The permission ``logging.logEntries.create`` is needed + on each project, organization, billing account, or + folder that is receiving new log entries, whether the + resource is specified in ``logName`` or in an individual + log entry. + + This corresponds to the ``log_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.api.monitored_resource_pb2.MonitoredResource`): + Optional. A default monitored resource object that is + assigned to all log entries in ``entries`` that do not + specify a value for ``resource``. Example: + + :: + + { "type": "gce_instance", + "labels": { + "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + + See [LogEntry][google.logging.v2.LogEntry]. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + labels (:class:`MutableMapping[str, str]`): + Optional. Default labels that are added to the + ``labels`` field of all log entries in ``entries``. If a + log entry already has a label with the same key as a + label in this parameter, then the log entry's label is + not changed. See [LogEntry][google.logging.v2.LogEntry]. + + This corresponds to the ``labels`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entries (:class:`MutableSequence[google.cloud.logging_v2.types.LogEntry]`): + Required. The log entries to send to Logging. The order + of log entries in this list does not matter. Values + supplied in this method's ``log_name``, ``resource``, + and ``labels`` fields are copied into those log entries + in this list that do not include values for their + corresponding fields. For more information, see the + [LogEntry][google.logging.v2.LogEntry] type. + + If the ``timestamp`` or ``insert_id`` fields are missing + in log entries, then this method supplies the current + time or a unique identifier, respectively. The supplied + values are chosen so that, among the log entries that + did not supply their own values, the entries earlier in + the list will sort before the entries later in the list. + See the ``entries.list`` method. + + Log entries with timestamps that are more than the `logs + retention + period `__ in + the past or more than 24 hours in the future will not be + available when calling ``entries.list``. However, those + log entries can still be `exported with + LogSinks `__. + + To improve throughput and to avoid exceeding the `quota + limit `__ for + calls to ``entries.write``, you should try to include + several log entries in this list, rather than calling + this method for each individual log entry. + + This corresponds to the ``entries`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.WriteLogEntriesResponse: + Result returned from WriteLogEntries. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [log_name, resource, labels, entries] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.WriteLogEntriesRequest): + request = logging.WriteLogEntriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if log_name is not None: + request.log_name = log_name + if resource is not None: + request.resource = resource + + if labels: + request.labels.update(labels) + if entries: + request.entries.extend(entries) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.write_log_entries + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesAsyncPager: + r"""Lists log entries. Use this method to retrieve log entries that + originated from a project/folder/organization/billing account. + For ways to export log entries, see `Exporting + Logs `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_log_entries(): + # Create a client + client = logging_v2.LoggingServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListLogEntriesRequest( + resource_names=['resource_names_value1', 'resource_names_value2'], + ) + + # Make the request + page_result = client.list_log_entries(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]]): + The request object. The parameters to ``ListLogEntries``. + resource_names (:class:`MutableSequence[str]`): + Required. Names of one or more parent resources from + which to retrieve log entries: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + May alternatively be one or more views: + + - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + + Projects listed in the ``project_ids`` field are added + to this list. A maximum of 100 resources may be + specified in a single request. + + This corresponds to the ``resource_names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Only log entries that match the filter are + returned. An empty filter matches all log entries in the + resources listed in ``resource_names``. Referencing a + parent resource that is not listed in ``resource_names`` + will cause the filter to return no results. The maximum + length of a filter is 20,000 characters. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + order_by (:class:`str`): + Optional. How the results should be sorted. Presently, + the only permitted values are ``"timestamp asc"`` + (default) and ``"timestamp desc"``. The first option + returns entries in order of increasing values of + ``LogEntry.timestamp`` (oldest first), and the second + option returns entries in order of decreasing timestamps + (newest first). Entries with equal timestamps are + returned in order of their ``insert_id`` values. + + This corresponds to the ``order_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesAsyncPager: + Result returned from ListLogEntries. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource_names, filter, order_by] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.ListLogEntriesRequest): + request = logging.ListLogEntriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if filter is not None: + request.filter = filter + if order_by is not None: + request.order_by = order_by + if resource_names: + request.resource_names.extend(resource_names) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_log_entries + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLogEntriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager: + r"""Lists the descriptors for monitored resource types + used by Logging. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_monitored_resource_descriptors(): + # Create a client + client = logging_v2.LoggingServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListMonitoredResourceDescriptorsRequest( + ) + + # Make the request + page_result = client.list_monitored_resource_descriptors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]]): + The request object. The parameters to + ListMonitoredResourceDescriptors + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsAsyncPager: + Result returned from + ListMonitoredResourceDescriptors. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest): + request = logging.ListMonitoredResourceDescriptorsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_monitored_resource_descriptors + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMonitoredResourceDescriptorsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsAsyncPager: + r"""Lists the logs in projects, organizations, folders, + or billing accounts. Only logs that have entries are + listed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_logs(): + # Create a client + client = logging_v2.LoggingServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListLogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_logs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListLogsRequest, dict]]): + The request object. The parameters to ListLogs. + parent (:class:`str`): + Required. The resource name to list logs for: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsAsyncPager: + Result returned from ListLogs. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.ListLogsRequest): + request = logging.ListLogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_logs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLogsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def tail_log_entries( + self, + requests: Optional[AsyncIterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]: + r"""Streaming read of log entries as they are ingested. + Until the stream is terminated, it will continue reading + logs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_tail_log_entries(): + # Create a client + client = logging_v2.LoggingServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.TailLogEntriesRequest( + resource_names=['resource_names_value1', 'resource_names_value2'], + ) + + # This method expects an iterator which contains + # 'logging_v2.TailLogEntriesRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.tail_log_entries(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.logging_v2.types.TailLogEntriesRequest`]): + The request object AsyncIterator. The parameters to ``TailLogEntries``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.cloud.logging_v2.types.TailLogEntriesResponse]: + Result returned from TailLogEntries. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.tail_log_entries + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "LoggingServiceV2AsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("LoggingServiceV2AsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/client.py new file mode 100644 index 0000000000000000000000000000000000000000..f247216f3a012df1e80980f992fbc2e910422e89 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -0,0 +1,1716 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import uuid +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.logging_v2.services.logging_service_v2 import pagers +from google.cloud.logging_v2.types import log_entry, logging + +from .transports.base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from .transports.grpc import LoggingServiceV2GrpcTransport +from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport + + +class LoggingServiceV2ClientMeta(type): + """Metaclass for the LoggingServiceV2 client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] + _transport_registry["grpc"] = LoggingServiceV2GrpcTransport + _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta): + """Service for ingesting and querying logs.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "logging.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LoggingServiceV2Client: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LoggingServiceV2Client: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LoggingServiceV2Transport: + """Returns the transport used by the client instance. + + Returns: + LoggingServiceV2Transport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def log_path( + project: str, + log: str, + ) -> str: + """Returns a fully-qualified log string.""" + return "projects/{project}/logs/{log}".format( + project=project, + log=log, + ) + + @staticmethod + def parse_log_path(path: str) -> Dict[str, str]: + """Parses a log path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = LoggingServiceV2Client._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = LoggingServiceV2Client._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = LoggingServiceV2Client._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = LoggingServiceV2Client._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the logging service v2 client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LoggingServiceV2Transport,Callable[..., LoggingServiceV2Transport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LoggingServiceV2Transport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + LoggingServiceV2Client._read_environment_variables() + ) + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = LoggingServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, LoggingServiceV2Transport) + if transport_provided: + # transport is a LoggingServiceV2Transport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(LoggingServiceV2Transport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or LoggingServiceV2Client._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[LoggingServiceV2Transport], + Callable[..., LoggingServiceV2Transport], + ] = ( + LoggingServiceV2Client.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LoggingServiceV2Transport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.logging_v2.LoggingServiceV2Client`.", + extra={ + "serviceName": "google.logging.v2.LoggingServiceV2", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.logging.v2.LoggingServiceV2", + "credentialsType": None, + }, + ) + + def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes all the log entries in a log for the \_Default Log + Bucket. The log reappears if it receives new entries. Log + entries written shortly before the delete operation might not be + deleted. Entries received after the delete operation with a + timestamp before the operation will be deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_log(): + # Create a client + client = logging_v2.LoggingServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteLogRequest( + log_name="log_name_value", + ) + + # Make the request + client.delete_log(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]): + The request object. The parameters to DeleteLog. + log_name (str): + Required. The resource name of the log to delete: + + - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` + - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` + - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` + + ``[LOG_ID]`` must be URL-encoded. For example, + ``"projects/my-project-id/logs/syslog"``, + ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``. + + For more information about log names, see + [LogEntry][google.logging.v2.LogEntry]. + + This corresponds to the ``log_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [log_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.DeleteLogRequest): + request = logging.DeleteLogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if log_name is not None: + request.log_name = log_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_log] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: + r"""Writes log entries to Logging. This API method is the + only way to send log entries to Logging. This method is + used, directly or indirectly, by the Logging agent + (fluentd) and all logging libraries configured to use + Logging. A single request may contain log entries for a + maximum of 1000 different resources (projects, + organizations, billing accounts or folders) + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_write_log_entries(): + # Create a client + client = logging_v2.LoggingServiceV2Client() + + # Initialize request argument(s) + entries = logging_v2.LogEntry() + entries.log_name = "log_name_value" + + request = logging_v2.WriteLogEntriesRequest( + entries=entries, + ) + + # Make the request + response = client.write_log_entries(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]): + The request object. The parameters to WriteLogEntries. + log_name (str): + Optional. A default log resource name that is assigned + to all log entries in ``entries`` that do not specify a + value for ``log_name``: + + - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` + - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` + - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` + + ``[LOG_ID]`` must be URL-encoded. For example: + + :: + + "projects/my-project-id/logs/syslog" + "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" + + The permission ``logging.logEntries.create`` is needed + on each project, organization, billing account, or + folder that is receiving new log entries, whether the + resource is specified in ``logName`` or in an individual + log entry. + + This corresponds to the ``log_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.api.monitored_resource_pb2.MonitoredResource): + Optional. A default monitored resource object that is + assigned to all log entries in ``entries`` that do not + specify a value for ``resource``. Example: + + :: + + { "type": "gce_instance", + "labels": { + "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + + See [LogEntry][google.logging.v2.LogEntry]. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + labels (MutableMapping[str, str]): + Optional. Default labels that are added to the + ``labels`` field of all log entries in ``entries``. If a + log entry already has a label with the same key as a + label in this parameter, then the log entry's label is + not changed. See [LogEntry][google.logging.v2.LogEntry]. + + This corresponds to the ``labels`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]): + Required. The log entries to send to Logging. The order + of log entries in this list does not matter. Values + supplied in this method's ``log_name``, ``resource``, + and ``labels`` fields are copied into those log entries + in this list that do not include values for their + corresponding fields. For more information, see the + [LogEntry][google.logging.v2.LogEntry] type. + + If the ``timestamp`` or ``insert_id`` fields are missing + in log entries, then this method supplies the current + time or a unique identifier, respectively. The supplied + values are chosen so that, among the log entries that + did not supply their own values, the entries earlier in + the list will sort before the entries later in the list. + See the ``entries.list`` method. + + Log entries with timestamps that are more than the `logs + retention + period `__ in + the past or more than 24 hours in the future will not be + available when calling ``entries.list``. However, those + log entries can still be `exported with + LogSinks `__. + + To improve throughput and to avoid exceeding the `quota + limit `__ for + calls to ``entries.write``, you should try to include + several log entries in this list, rather than calling + this method for each individual log entry. + + This corresponds to the ``entries`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.WriteLogEntriesResponse: + Result returned from WriteLogEntries. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [log_name, resource, labels, entries] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.WriteLogEntriesRequest): + request = logging.WriteLogEntriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if log_name is not None: + request.log_name = log_name + if resource is not None: + request.resource = resource + if labels is not None: + request.labels = labels + if entries is not None: + request.entries = entries + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_log_entries] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: + r"""Lists log entries. Use this method to retrieve log entries that + originated from a project/folder/organization/billing account. + For ways to export log entries, see `Exporting + Logs `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_log_entries(): + # Create a client + client = logging_v2.LoggingServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListLogEntriesRequest( + resource_names=['resource_names_value1', 'resource_names_value2'], + ) + + # Make the request + page_result = client.list_log_entries(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]): + The request object. The parameters to ``ListLogEntries``. + resource_names (MutableSequence[str]): + Required. Names of one or more parent resources from + which to retrieve log entries: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + May alternatively be one or more views: + + - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + + Projects listed in the ``project_ids`` field are added + to this list. A maximum of 100 resources may be + specified in a single request. + + This corresponds to the ``resource_names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Only log entries that match the filter are + returned. An empty filter matches all log entries in the + resources listed in ``resource_names``. Referencing a + parent resource that is not listed in ``resource_names`` + will cause the filter to return no results. The maximum + length of a filter is 20,000 characters. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + order_by (str): + Optional. How the results should be sorted. Presently, + the only permitted values are ``"timestamp asc"`` + (default) and ``"timestamp desc"``. The first option + returns entries in order of increasing values of + ``LogEntry.timestamp`` (oldest first), and the second + option returns entries in order of decreasing timestamps + (newest first). Entries with equal timestamps are + returned in order of their ``insert_id`` values. + + This corresponds to the ``order_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesPager: + Result returned from ListLogEntries. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [resource_names, filter, order_by] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.ListLogEntriesRequest): + request = logging.ListLogEntriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_names is not None: + request.resource_names = resource_names + if filter is not None: + request.filter = filter + if order_by is not None: + request.order_by = order_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_log_entries] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLogEntriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: + r"""Lists the descriptors for monitored resource types + used by Logging. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_monitored_resource_descriptors(): + # Create a client + client = logging_v2.LoggingServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListMonitoredResourceDescriptorsRequest( + ) + + # Make the request + page_result = client.list_monitored_resource_descriptors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]): + The request object. The parameters to + ListMonitoredResourceDescriptors + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsPager: + Result returned from + ListMonitoredResourceDescriptors. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest): + request = logging.ListMonitoredResourceDescriptorsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_monitored_resource_descriptors + ] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMonitoredResourceDescriptorsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: + r"""Lists the logs in projects, organizations, folders, + or billing accounts. Only logs that have entries are + listed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_logs(): + # Create a client + client = logging_v2.LoggingServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListLogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_logs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListLogsRequest, dict]): + The request object. The parameters to ListLogs. + parent (str): + Required. The resource name to list logs for: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsPager: + Result returned from ListLogs. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging.ListLogsRequest): + request = logging.ListLogsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_logs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLogsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def tail_log_entries( + self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: + r"""Streaming read of log entries as they are ingested. + Until the stream is terminated, it will continue reading + logs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_tail_log_entries(): + # Create a client + client = logging_v2.LoggingServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.TailLogEntriesRequest( + resource_names=['resource_names_value1', 'resource_names_value2'], + ) + + # This method expects an iterator which contains + # 'logging_v2.TailLogEntriesRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.tail_log_entries(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.logging_v2.types.TailLogEntriesRequest]): + The request object iterator. The parameters to ``TailLogEntries``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]: + Result returned from TailLogEntries. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.tail_log_entries] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LoggingServiceV2Client": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("LoggingServiceV2Client",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..b0929c2543f4527de1ecbee7fe82f3e37f47c151 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/pagers.py @@ -0,0 +1,517 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore + +from google.cloud.logging_v2.types import log_entry, logging + + +class ListLogEntriesPager: + """A pager for iterating through ``list_log_entries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLogEntries`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging.ListLogEntriesResponse], + request: logging.ListLogEntriesRequest, + response: logging.ListLogEntriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLogEntriesRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLogEntriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging.ListLogEntriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging.ListLogEntriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[log_entry.LogEntry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLogEntriesAsyncPager: + """A pager for iterating through ``list_log_entries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLogEntries`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging.ListLogEntriesResponse]], + request: logging.ListLogEntriesRequest, + response: logging.ListLogEntriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLogEntriesRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLogEntriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging.ListLogEntriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging.ListLogEntriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[log_entry.LogEntry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMonitoredResourceDescriptorsPager: + """A pager for iterating through ``list_monitored_resource_descriptors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_descriptors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMonitoredResourceDescriptors`` requests and continue to iterate + through the ``resource_descriptors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging.ListMonitoredResourceDescriptorsResponse], + request: logging.ListMonitoredResourceDescriptorsRequest, + response: logging.ListMonitoredResourceDescriptorsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging.ListMonitoredResourceDescriptorsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging.ListMonitoredResourceDescriptorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[monitored_resource_pb2.MonitoredResourceDescriptor]: + for page in self.pages: + yield from page.resource_descriptors + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMonitoredResourceDescriptorsAsyncPager: + """A pager for iterating through ``list_monitored_resource_descriptors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_descriptors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMonitoredResourceDescriptors`` requests and continue to iterate + through the ``resource_descriptors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[logging.ListMonitoredResourceDescriptorsResponse] + ], + request: logging.ListMonitoredResourceDescriptorsRequest, + response: logging.ListMonitoredResourceDescriptorsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging.ListMonitoredResourceDescriptorsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[logging.ListMonitoredResourceDescriptorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[monitored_resource_pb2.MonitoredResourceDescriptor]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_descriptors: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLogsPager: + """A pager for iterating through ``list_logs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``log_names`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLogs`` requests and continue to iterate + through the ``log_names`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLogsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging.ListLogsResponse], + request: logging.ListLogsRequest, + response: logging.ListLogsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLogsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLogsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging.ListLogsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging.ListLogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[str]: + for page in self.pages: + yield from page.log_names + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLogsAsyncPager: + """A pager for iterating through ``list_logs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``log_names`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLogs`` requests and continue to iterate + through the ``log_names`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLogsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging.ListLogsResponse]], + request: logging.ListLogsRequest, + response: logging.ListLogsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLogsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLogsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging.ListLogsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging.ListLogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[str]: + async def async_generator(): + async for page in self.pages: + for response in page.log_names: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..880f7e966313067be1ff24f579ca049f4b66b722 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import LoggingServiceV2Transport +from .grpc import LoggingServiceV2GrpcTransport +from .grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] +_transport_registry["grpc"] = LoggingServiceV2GrpcTransport +_transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport + +__all__ = ( + "LoggingServiceV2Transport", + "LoggingServiceV2GrpcTransport", + "LoggingServiceV2GrpcAsyncIOTransport", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..05b73ee53a9365cac56916bbdfedf48280f18214 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2.types import logging + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class LoggingServiceV2Transport(abc.ABC): + """Abstract transport class for LoggingServiceV2.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", + ) + + DEFAULT_HOST: str = "logging.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.delete_log: gapic_v1.method.wrap_method( + self.delete_log, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.write_log_entries: gapic_v1.method.wrap_method( + self.write_log_entries, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_log_entries: gapic_v1.method.wrap_method( + self.list_log_entries, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_monitored_resource_descriptors: gapic_v1.method.wrap_method( + self.list_monitored_resource_descriptors, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_logs: gapic_v1.method.wrap_method( + self.list_logs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.tail_log_entries: gapic_v1.method.wrap_method( + self.tail_log_entries, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def delete_log( + self, + ) -> Callable[ + [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def write_log_entries( + self, + ) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_log_entries( + self, + ) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_logs( + self, + ) -> Callable[ + [logging.ListLogsRequest], + Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], + ]: + raise NotImplementedError() + + @property + def tail_log_entries( + self, + ) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("LoggingServiceV2Transport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..b9564e9e04177cf085d3d09cd9d854f459bbfd4f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -0,0 +1,569 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.logging_v2.types import logging + +from .base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.logging.v2.LoggingServiceV2", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.logging.v2.LoggingServiceV2", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LoggingServiceV2GrpcTransport(LoggingServiceV2Transport): + """gRPC backend transport for LoggingServiceV2. + + Service for ingesting and querying logs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: + r"""Return a callable for the delete log method over gRPC. + + Deletes all the log entries in a log for the \_Default Log + Bucket. The log reappears if it receives new entries. Log + entries written shortly before the delete operation might not be + deleted. Entries received after the delete operation with a + timestamp before the operation will be deleted. + + Returns: + Callable[[~.DeleteLogRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_log" not in self._stubs: + self._stubs["delete_log"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/DeleteLog", + request_serializer=logging.DeleteLogRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_log"] + + @property + def write_log_entries( + self, + ) -> Callable[[logging.WriteLogEntriesRequest], logging.WriteLogEntriesResponse]: + r"""Return a callable for the write log entries method over gRPC. + + Writes log entries to Logging. This API method is the + only way to send log entries to Logging. This method is + used, directly or indirectly, by the Logging agent + (fluentd) and all logging libraries configured to use + Logging. A single request may contain log entries for a + maximum of 1000 different resources (projects, + organizations, billing accounts or folders) + + Returns: + Callable[[~.WriteLogEntriesRequest], + ~.WriteLogEntriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "write_log_entries" not in self._stubs: + self._stubs["write_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/WriteLogEntries", + request_serializer=logging.WriteLogEntriesRequest.serialize, + response_deserializer=logging.WriteLogEntriesResponse.deserialize, + ) + return self._stubs["write_log_entries"] + + @property + def list_log_entries( + self, + ) -> Callable[[logging.ListLogEntriesRequest], logging.ListLogEntriesResponse]: + r"""Return a callable for the list log entries method over gRPC. + + Lists log entries. Use this method to retrieve log entries that + originated from a project/folder/organization/billing account. + For ways to export log entries, see `Exporting + Logs `__. + + Returns: + Callable[[~.ListLogEntriesRequest], + ~.ListLogEntriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_log_entries" not in self._stubs: + self._stubs["list_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogEntries", + request_serializer=logging.ListLogEntriesRequest.serialize, + response_deserializer=logging.ListLogEntriesResponse.deserialize, + ) + return self._stubs["list_log_entries"] + + @property + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + logging.ListMonitoredResourceDescriptorsResponse, + ]: + r"""Return a callable for the list monitored resource + descriptors method over gRPC. + + Lists the descriptors for monitored resource types + used by Logging. + + Returns: + Callable[[~.ListMonitoredResourceDescriptorsRequest], + ~.ListMonitoredResourceDescriptorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_monitored_resource_descriptors" not in self._stubs: + self._stubs["list_monitored_resource_descriptors"] = ( + self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", + request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, + response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, + ) + ) + return self._stubs["list_monitored_resource_descriptors"] + + @property + def list_logs( + self, + ) -> Callable[[logging.ListLogsRequest], logging.ListLogsResponse]: + r"""Return a callable for the list logs method over gRPC. + + Lists the logs in projects, organizations, folders, + or billing accounts. Only logs that have entries are + listed. + + Returns: + Callable[[~.ListLogsRequest], + ~.ListLogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_logs" not in self._stubs: + self._stubs["list_logs"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogs", + request_serializer=logging.ListLogsRequest.serialize, + response_deserializer=logging.ListLogsResponse.deserialize, + ) + return self._stubs["list_logs"] + + @property + def tail_log_entries( + self, + ) -> Callable[[logging.TailLogEntriesRequest], logging.TailLogEntriesResponse]: + r"""Return a callable for the tail log entries method over gRPC. + + Streaming read of log entries as they are ingested. + Until the stream is terminated, it will continue reading + logs. + + Returns: + Callable[[~.TailLogEntriesRequest], + ~.TailLogEntriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "tail_log_entries" not in self._stubs: + self._stubs["tail_log_entries"] = self._logged_channel.stream_stream( + "/google.logging.v2.LoggingServiceV2/TailLogEntries", + request_serializer=logging.TailLogEntriesRequest.serialize, + response_deserializer=logging.TailLogEntriesResponse.deserialize, + ) + return self._stubs["tail_log_entries"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("LoggingServiceV2GrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..63383e7ae17f68e92e2f7bc13dabda4219bb00b8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py @@ -0,0 +1,706 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.logging_v2.types import logging + +from .base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from .grpc import LoggingServiceV2GrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.logging.v2.LoggingServiceV2", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.logging.v2.LoggingServiceV2", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LoggingServiceV2GrpcAsyncIOTransport(LoggingServiceV2Transport): + """gRPC AsyncIO backend transport for LoggingServiceV2. + + Service for ingesting and querying logs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def delete_log( + self, + ) -> Callable[[logging.DeleteLogRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete log method over gRPC. + + Deletes all the log entries in a log for the \_Default Log + Bucket. The log reappears if it receives new entries. Log + entries written shortly before the delete operation might not be + deleted. Entries received after the delete operation with a + timestamp before the operation will be deleted. + + Returns: + Callable[[~.DeleteLogRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_log" not in self._stubs: + self._stubs["delete_log"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/DeleteLog", + request_serializer=logging.DeleteLogRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_log"] + + @property + def write_log_entries( + self, + ) -> Callable[ + [logging.WriteLogEntriesRequest], Awaitable[logging.WriteLogEntriesResponse] + ]: + r"""Return a callable for the write log entries method over gRPC. + + Writes log entries to Logging. This API method is the + only way to send log entries to Logging. This method is + used, directly or indirectly, by the Logging agent + (fluentd) and all logging libraries configured to use + Logging. A single request may contain log entries for a + maximum of 1000 different resources (projects, + organizations, billing accounts or folders) + + Returns: + Callable[[~.WriteLogEntriesRequest], + Awaitable[~.WriteLogEntriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "write_log_entries" not in self._stubs: + self._stubs["write_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/WriteLogEntries", + request_serializer=logging.WriteLogEntriesRequest.serialize, + response_deserializer=logging.WriteLogEntriesResponse.deserialize, + ) + return self._stubs["write_log_entries"] + + @property + def list_log_entries( + self, + ) -> Callable[ + [logging.ListLogEntriesRequest], Awaitable[logging.ListLogEntriesResponse] + ]: + r"""Return a callable for the list log entries method over gRPC. + + Lists log entries. Use this method to retrieve log entries that + originated from a project/folder/organization/billing account. + For ways to export log entries, see `Exporting + Logs `__. + + Returns: + Callable[[~.ListLogEntriesRequest], + Awaitable[~.ListLogEntriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_log_entries" not in self._stubs: + self._stubs["list_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogEntries", + request_serializer=logging.ListLogEntriesRequest.serialize, + response_deserializer=logging.ListLogEntriesResponse.deserialize, + ) + return self._stubs["list_log_entries"] + + @property + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Awaitable[logging.ListMonitoredResourceDescriptorsResponse], + ]: + r"""Return a callable for the list monitored resource + descriptors method over gRPC. + + Lists the descriptors for monitored resource types + used by Logging. + + Returns: + Callable[[~.ListMonitoredResourceDescriptorsRequest], + Awaitable[~.ListMonitoredResourceDescriptorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_monitored_resource_descriptors" not in self._stubs: + self._stubs["list_monitored_resource_descriptors"] = ( + self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", + request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, + response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, + ) + ) + return self._stubs["list_monitored_resource_descriptors"] + + @property + def list_logs( + self, + ) -> Callable[[logging.ListLogsRequest], Awaitable[logging.ListLogsResponse]]: + r"""Return a callable for the list logs method over gRPC. + + Lists the logs in projects, organizations, folders, + or billing accounts. Only logs that have entries are + listed. + + Returns: + Callable[[~.ListLogsRequest], + Awaitable[~.ListLogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_logs" not in self._stubs: + self._stubs["list_logs"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogs", + request_serializer=logging.ListLogsRequest.serialize, + response_deserializer=logging.ListLogsResponse.deserialize, + ) + return self._stubs["list_logs"] + + @property + def tail_log_entries( + self, + ) -> Callable[ + [logging.TailLogEntriesRequest], Awaitable[logging.TailLogEntriesResponse] + ]: + r"""Return a callable for the tail log entries method over gRPC. + + Streaming read of log entries as they are ingested. + Until the stream is terminated, it will continue reading + logs. + + Returns: + Callable[[~.TailLogEntriesRequest], + Awaitable[~.TailLogEntriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "tail_log_entries" not in self._stubs: + self._stubs["tail_log_entries"] = self._logged_channel.stream_stream( + "/google.logging.v2.LoggingServiceV2/TailLogEntries", + request_serializer=logging.TailLogEntriesRequest.serialize, + response_deserializer=logging.TailLogEntriesResponse.deserialize, + ) + return self._stubs["tail_log_entries"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.delete_log: self._wrap_method( + self.delete_log, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.write_log_entries: self._wrap_method( + self.write_log_entries, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_log_entries: self._wrap_method( + self.list_log_entries, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_monitored_resource_descriptors: self._wrap_method( + self.list_monitored_resource_descriptors, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_logs: self._wrap_method( + self.list_logs, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.tail_log_entries: self._wrap_method( + self.tail_log_entries, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("LoggingServiceV2GrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e23af6bce2c7ab3bde03ba4de195944e9669767 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import MetricsServiceV2AsyncClient +from .client import MetricsServiceV2Client + +__all__ = ( + "MetricsServiceV2Client", + "MetricsServiceV2AsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d06534be76c49a054da72daabbf28bd82147fa5a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/async_client.py @@ -0,0 +1,1138 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +import uuid +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api.distribution_pb2 as distribution_pb2 # type: ignore +import google.api.metric_pb2 as metric_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.logging_v2.services.metrics_service_v2 import pagers +from google.cloud.logging_v2.types import logging_metrics + +from .client import MetricsServiceV2Client +from .transports.base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class MetricsServiceV2AsyncClient: + """Service for configuring logs-based metrics.""" + + _client: MetricsServiceV2Client + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = MetricsServiceV2Client.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = MetricsServiceV2Client._DEFAULT_UNIVERSE + + log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path) + parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path) + common_billing_account_path = staticmethod( + MetricsServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + MetricsServiceV2Client.parse_common_billing_account_path + ) + common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path) + parse_common_folder_path = staticmethod( + MetricsServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + MetricsServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + MetricsServiceV2Client.parse_common_organization_path + ) + common_project_path = staticmethod(MetricsServiceV2Client.common_project_path) + parse_common_project_path = staticmethod( + MetricsServiceV2Client.parse_common_project_path + ) + common_location_path = staticmethod(MetricsServiceV2Client.common_location_path) + parse_common_location_path = staticmethod( + MetricsServiceV2Client.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + MetricsServiceV2AsyncClient: The constructed client. + """ + sa_info_func = ( + MetricsServiceV2Client.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(MetricsServiceV2AsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + MetricsServiceV2AsyncClient: The constructed client. + """ + sa_file_func = ( + MetricsServiceV2Client.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(MetricsServiceV2AsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return MetricsServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> MetricsServiceV2Transport: + """Returns the transport used by the client instance. + + Returns: + MetricsServiceV2Transport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = MetricsServiceV2Client.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the metrics service v2 async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,MetricsServiceV2Transport,Callable[..., MetricsServiceV2Transport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the MetricsServiceV2Transport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = MetricsServiceV2Client( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.logging_v2.MetricsServiceV2AsyncClient`.", + extra={ + "serviceName": "google.logging.v2.MetricsServiceV2", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.logging.v2.MetricsServiceV2", + "credentialsType": None, + }, + ) + + async def list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsAsyncPager: + r"""Lists logs-based metrics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_list_log_metrics(): + # Create a client + client = logging_v2.MetricsServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.ListLogMetricsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_log_metrics(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]]): + The request object. The parameters to ListLogMetrics. + parent (:class:`str`): + Required. The name of the project containing the + metrics: + + :: + + "projects/[PROJECT_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsAsyncPager: + Result returned from ListLogMetrics. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.ListLogMetricsRequest): + request = logging_metrics.ListLogMetricsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_log_metrics + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLogMetricsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: + r"""Gets a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_get_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.GetLogMetricRequest( + metric_name="metric_name_value", + ) + + # Make the request + response = await client.get_log_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]]): + The request object. The parameters to GetLogMetric. + metric_name (:class:`str`): + Required. The resource name of the desired metric: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + This corresponds to the ``metric_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogMetric: + Describes a logs-based metric. The + value of the metric is the number of log + entries that match a logs filter in a + given time interval. + + Logs-based metrics can also be used to + extract values from logs and create a + distribution of the values. The + distribution records the statistics of + the extracted values along with an + optional histogram of the values as + specified by the bucket options. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [metric_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.GetLogMetricRequest): + request = logging_metrics.GetLogMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metric_name is not None: + request.metric_name = metric_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_log_metric + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: + r"""Creates a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_create_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2AsyncClient() + + # Initialize request argument(s) + metric = logging_v2.LogMetric() + metric.name = "name_value" + metric.filter = "filter_value" + + request = logging_v2.CreateLogMetricRequest( + parent="parent_value", + metric=metric, + ) + + # Make the request + response = await client.create_log_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]]): + The request object. The parameters to CreateLogMetric. + parent (:class:`str`): + Required. The resource name of the project in which to + create the metric: + + :: + + "projects/[PROJECT_ID]" + + The new metric must be provided in the request. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metric (:class:`google.cloud.logging_v2.types.LogMetric`): + Required. The new logs-based metric, + which must not have an identifier that + already exists. + + This corresponds to the ``metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogMetric: + Describes a logs-based metric. The + value of the metric is the number of log + entries that match a logs filter in a + given time interval. + + Logs-based metrics can also be used to + extract values from logs and create a + distribution of the values. The + distribution records the statistics of + the extracted values along with an + optional histogram of the values as + specified by the bucket options. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, metric] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.CreateLogMetricRequest): + request = logging_metrics.CreateLogMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metric is not None: + request.metric = metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_log_metric + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: + r"""Creates or updates a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_update_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2AsyncClient() + + # Initialize request argument(s) + metric = logging_v2.LogMetric() + metric.name = "name_value" + metric.filter = "filter_value" + + request = logging_v2.UpdateLogMetricRequest( + metric_name="metric_name_value", + metric=metric, + ) + + # Make the request + response = await client.update_log_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]]): + The request object. The parameters to UpdateLogMetric. + metric_name (:class:`str`): + Required. The resource name of the metric to update: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + The updated metric must be provided in the request and + it's ``name`` field must be the same as ``[METRIC_ID]`` + If the metric does not exist in ``[PROJECT_ID]``, then a + new metric is created. + + This corresponds to the ``metric_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metric (:class:`google.cloud.logging_v2.types.LogMetric`): + Required. The updated metric. + This corresponds to the ``metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogMetric: + Describes a logs-based metric. The + value of the metric is the number of log + entries that match a logs filter in a + given time interval. + + Logs-based metrics can also be used to + extract values from logs and create a + distribution of the values. The + distribution records the statistics of + the extracted values along with an + optional histogram of the values as + specified by the bucket options. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [metric_name, metric] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.UpdateLogMetricRequest): + request = logging_metrics.UpdateLogMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metric_name is not None: + request.metric_name = metric_name + if metric is not None: + request.metric = metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_log_metric + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + async def sample_delete_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2AsyncClient() + + # Initialize request argument(s) + request = logging_v2.DeleteLogMetricRequest( + metric_name="metric_name_value", + ) + + # Make the request + await client.delete_log_metric(request=request) + + Args: + request (Optional[Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]]): + The request object. The parameters to DeleteLogMetric. + metric_name (:class:`str`): + Required. The resource name of the metric to delete: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + This corresponds to the ``metric_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [metric_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.DeleteLogMetricRequest): + request = logging_metrics.DeleteLogMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metric_name is not None: + request.metric_name = metric_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_log_metric + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "MetricsServiceV2AsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("MetricsServiceV2AsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/client.py new file mode 100644 index 0000000000000000000000000000000000000000..70e3c42323a316a9719a7b816cc92284962ba605 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -0,0 +1,1565 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import uuid +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api.distribution_pb2 as distribution_pb2 # type: ignore +import google.api.metric_pb2 as metric_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.logging_v2.services.metrics_service_v2 import pagers +from google.cloud.logging_v2.types import logging_metrics + +from .transports.base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from .transports.grpc import MetricsServiceV2GrpcTransport +from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport + + +class MetricsServiceV2ClientMeta(type): + """Metaclass for the MetricsServiceV2 client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] + _transport_registry["grpc"] = MetricsServiceV2GrpcTransport + _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta): + """Service for configuring logs-based metrics.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "logging.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + MetricsServiceV2Client: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + MetricsServiceV2Client: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> MetricsServiceV2Transport: + """Returns the transport used by the client instance. + + Returns: + MetricsServiceV2Transport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def log_metric_path( + project: str, + metric: str, + ) -> str: + """Returns a fully-qualified log_metric string.""" + return "projects/{project}/metrics/{metric}".format( + project=project, + metric=metric, + ) + + @staticmethod + def parse_log_metric_path(path: str) -> Dict[str, str]: + """Parses a log_metric path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = MetricsServiceV2Client._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = MetricsServiceV2Client._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = MetricsServiceV2Client._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the metrics service v2 client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,MetricsServiceV2Transport,Callable[..., MetricsServiceV2Transport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the MetricsServiceV2Transport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + MetricsServiceV2Client._read_environment_variables() + ) + self._client_cert_source = MetricsServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = MetricsServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, MetricsServiceV2Transport) + if transport_provided: + # transport is a MetricsServiceV2Transport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(MetricsServiceV2Transport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or MetricsServiceV2Client._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[MetricsServiceV2Transport], + Callable[..., MetricsServiceV2Transport], + ] = ( + MetricsServiceV2Client.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., MetricsServiceV2Transport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.logging_v2.MetricsServiceV2Client`.", + extra={ + "serviceName": "google.logging.v2.MetricsServiceV2", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.logging.v2.MetricsServiceV2", + "credentialsType": None, + }, + ) + + def list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: + r"""Lists logs-based metrics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_list_log_metrics(): + # Create a client + client = logging_v2.MetricsServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.ListLogMetricsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_log_metrics(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]): + The request object. The parameters to ListLogMetrics. + parent (str): + Required. The name of the project containing the + metrics: + + :: + + "projects/[PROJECT_ID]" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager: + Result returned from ListLogMetrics. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.ListLogMetricsRequest): + request = logging_metrics.ListLogMetricsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_log_metrics] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLogMetricsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: + r"""Gets a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_get_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.GetLogMetricRequest( + metric_name="metric_name_value", + ) + + # Make the request + response = client.get_log_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]): + The request object. The parameters to GetLogMetric. + metric_name (str): + Required. The resource name of the desired metric: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + This corresponds to the ``metric_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogMetric: + Describes a logs-based metric. The + value of the metric is the number of log + entries that match a logs filter in a + given time interval. + + Logs-based metrics can also be used to + extract values from logs and create a + distribution of the values. The + distribution records the statistics of + the extracted values along with an + optional histogram of the values as + specified by the bucket options. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [metric_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.GetLogMetricRequest): + request = logging_metrics.GetLogMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metric_name is not None: + request.metric_name = metric_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_log_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: + r"""Creates a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_create_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2Client() + + # Initialize request argument(s) + metric = logging_v2.LogMetric() + metric.name = "name_value" + metric.filter = "filter_value" + + request = logging_v2.CreateLogMetricRequest( + parent="parent_value", + metric=metric, + ) + + # Make the request + response = client.create_log_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]): + The request object. The parameters to CreateLogMetric. + parent (str): + Required. The resource name of the project in which to + create the metric: + + :: + + "projects/[PROJECT_ID]" + + The new metric must be provided in the request. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metric (google.cloud.logging_v2.types.LogMetric): + Required. The new logs-based metric, + which must not have an identifier that + already exists. + + This corresponds to the ``metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogMetric: + Describes a logs-based metric. The + value of the metric is the number of log + entries that match a logs filter in a + given time interval. + + Logs-based metrics can also be used to + extract values from logs and create a + distribution of the values. The + distribution records the statistics of + the extracted values along with an + optional histogram of the values as + specified by the bucket options. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, metric] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.CreateLogMetricRequest): + request = logging_metrics.CreateLogMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metric is not None: + request.metric = metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_log_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: + r"""Creates or updates a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_update_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2Client() + + # Initialize request argument(s) + metric = logging_v2.LogMetric() + metric.name = "name_value" + metric.filter = "filter_value" + + request = logging_v2.UpdateLogMetricRequest( + metric_name="metric_name_value", + metric=metric, + ) + + # Make the request + response = client.update_log_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]): + The request object. The parameters to UpdateLogMetric. + metric_name (str): + Required. The resource name of the metric to update: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + The updated metric must be provided in the request and + it's ``name`` field must be the same as ``[METRIC_ID]`` + If the metric does not exist in ``[PROJECT_ID]``, then a + new metric is created. + + This corresponds to the ``metric_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metric (google.cloud.logging_v2.types.LogMetric): + Required. The updated metric. + This corresponds to the ``metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.logging_v2.types.LogMetric: + Describes a logs-based metric. The + value of the metric is the number of log + entries that match a logs filter in a + given time interval. + + Logs-based metrics can also be used to + extract values from logs and create a + distribution of the values. The + distribution records the statistics of + the extracted values along with an + optional histogram of the values as + specified by the bucket options. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [metric_name, metric] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.UpdateLogMetricRequest): + request = logging_metrics.UpdateLogMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metric_name is not None: + request.metric_name = metric_name + if metric is not None: + request.metric = metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_log_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a logs-based metric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import logging_v2 + + def sample_delete_log_metric(): + # Create a client + client = logging_v2.MetricsServiceV2Client() + + # Initialize request argument(s) + request = logging_v2.DeleteLogMetricRequest( + metric_name="metric_name_value", + ) + + # Make the request + client.delete_log_metric(request=request) + + Args: + request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]): + The request object. The parameters to DeleteLogMetric. + metric_name (str): + Required. The resource name of the metric to delete: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + This corresponds to the ``metric_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [metric_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, logging_metrics.DeleteLogMetricRequest): + request = logging_metrics.DeleteLogMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metric_name is not None: + request.metric_name = metric_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_log_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "MetricsServiceV2Client": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("MetricsServiceV2Client",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..e296aebedbf823196c6a1953504288238f5c9ede --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.logging_v2.types import logging_metrics + + +class ListLogMetricsPager: + """A pager for iterating through ``list_log_metrics`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``metrics`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLogMetrics`` requests and continue to iterate + through the ``metrics`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., logging_metrics.ListLogMetricsResponse], + request: logging_metrics.ListLogMetricsRequest, + response: logging_metrics.ListLogMetricsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLogMetricsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLogMetricsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_metrics.ListLogMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[logging_metrics.ListLogMetricsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[logging_metrics.LogMetric]: + for page in self.pages: + yield from page.metrics + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLogMetricsAsyncPager: + """A pager for iterating through ``list_log_metrics`` requests. + + This class thinly wraps an initial + :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``metrics`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLogMetrics`` requests and continue to iterate + through the ``metrics`` field on the + corresponding responses. + + All the usual :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[logging_metrics.ListLogMetricsResponse]], + request: logging_metrics.ListLogMetricsRequest, + response: logging_metrics.ListLogMetricsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.logging_v2.types.ListLogMetricsRequest): + The initial request object. + response (google.cloud.logging_v2.types.ListLogMetricsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = logging_metrics.ListLogMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[logging_metrics.ListLogMetricsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[logging_metrics.LogMetric]: + async def async_generator(): + async for page in self.pages: + for response in page.metrics: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10e38acd8596f9812f535f64c6cee77a9bc58570 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import MetricsServiceV2Transport +from .grpc import MetricsServiceV2GrpcTransport +from .grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] +_transport_registry["grpc"] = MetricsServiceV2GrpcTransport +_transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport + +__all__ = ( + "MetricsServiceV2Transport", + "MetricsServiceV2GrpcTransport", + "MetricsServiceV2GrpcAsyncIOTransport", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..866353cfe0e93b2640ec4f2d1c64715e69263e27 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -0,0 +1,331 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2.types import logging_metrics + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class MetricsServiceV2Transport(abc.ABC): + """Abstract transport class for MetricsServiceV2.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", + ) + + DEFAULT_HOST: str = "logging.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_log_metrics: gapic_v1.method.wrap_method( + self.list_log_metrics, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_log_metric: gapic_v1.method.wrap_method( + self.get_log_metric, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_log_metric: gapic_v1.method.wrap_method( + self.create_log_metric, + default_timeout=60.0, + client_info=client_info, + ), + self.update_log_metric: gapic_v1.method.wrap_method( + self.update_log_metric, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_log_metric: gapic_v1.method.wrap_method( + self.delete_log_metric, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_log_metric( + self, + ) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: + raise NotImplementedError() + + @property + def create_log_metric( + self, + ) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: + raise NotImplementedError() + + @property + def update_log_metric( + self, + ) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: + raise NotImplementedError() + + @property + def delete_log_metric( + self, + ) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("MetricsServiceV2Transport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..ffa66c672c5fd5653966e1128210a67c72a5882f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.logging_v2.types import logging_metrics + +from .base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.logging.v2.MetricsServiceV2", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.logging.v2.MetricsServiceV2", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport): + """gRPC backend transport for MetricsServiceV2. + + Service for configuring logs-based metrics. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse + ]: + r"""Return a callable for the list log metrics method over gRPC. + + Lists logs-based metrics. + + Returns: + Callable[[~.ListLogMetricsRequest], + ~.ListLogMetricsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_log_metrics" not in self._stubs: + self._stubs["list_log_metrics"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/ListLogMetrics", + request_serializer=logging_metrics.ListLogMetricsRequest.serialize, + response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, + ) + return self._stubs["list_log_metrics"] + + @property + def get_log_metric( + self, + ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]: + r"""Return a callable for the get log metric method over gRPC. + + Gets a logs-based metric. + + Returns: + Callable[[~.GetLogMetricRequest], + ~.LogMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_log_metric" not in self._stubs: + self._stubs["get_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/GetLogMetric", + request_serializer=logging_metrics.GetLogMetricRequest.serialize, + response_deserializer=logging_metrics.LogMetric.deserialize, + ) + return self._stubs["get_log_metric"] + + @property + def create_log_metric( + self, + ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]: + r"""Return a callable for the create log metric method over gRPC. + + Creates a logs-based metric. + + Returns: + Callable[[~.CreateLogMetricRequest], + ~.LogMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_log_metric" not in self._stubs: + self._stubs["create_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/CreateLogMetric", + request_serializer=logging_metrics.CreateLogMetricRequest.serialize, + response_deserializer=logging_metrics.LogMetric.deserialize, + ) + return self._stubs["create_log_metric"] + + @property + def update_log_metric( + self, + ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]: + r"""Return a callable for the update log metric method over gRPC. + + Creates or updates a logs-based metric. + + Returns: + Callable[[~.UpdateLogMetricRequest], + ~.LogMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_log_metric" not in self._stubs: + self._stubs["update_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", + request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, + response_deserializer=logging_metrics.LogMetric.deserialize, + ) + return self._stubs["update_log_metric"] + + @property + def delete_log_metric( + self, + ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]: + r"""Return a callable for the delete log metric method over gRPC. + + Deletes a logs-based metric. + + Returns: + Callable[[~.DeleteLogMetricRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_log_metric" not in self._stubs: + self._stubs["delete_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", + request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_log_metric"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("MetricsServiceV2GrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..2bbdb05165083ede3840b34b168ffe5a5297b98d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py @@ -0,0 +1,632 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.logging_v2.types import logging_metrics + +from .base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from .grpc import MetricsServiceV2GrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.logging.v2.MetricsServiceV2", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.logging.v2.MetricsServiceV2", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MetricsServiceV2GrpcAsyncIOTransport(MetricsServiceV2Transport): + """gRPC AsyncIO backend transport for MetricsServiceV2. + + Service for configuring logs-based metrics. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'logging.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Awaitable[logging_metrics.ListLogMetricsResponse], + ]: + r"""Return a callable for the list log metrics method over gRPC. + + Lists logs-based metrics. + + Returns: + Callable[[~.ListLogMetricsRequest], + Awaitable[~.ListLogMetricsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_log_metrics" not in self._stubs: + self._stubs["list_log_metrics"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/ListLogMetrics", + request_serializer=logging_metrics.ListLogMetricsRequest.serialize, + response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, + ) + return self._stubs["list_log_metrics"] + + @property + def get_log_metric( + self, + ) -> Callable[ + [logging_metrics.GetLogMetricRequest], Awaitable[logging_metrics.LogMetric] + ]: + r"""Return a callable for the get log metric method over gRPC. + + Gets a logs-based metric. + + Returns: + Callable[[~.GetLogMetricRequest], + Awaitable[~.LogMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_log_metric" not in self._stubs: + self._stubs["get_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/GetLogMetric", + request_serializer=logging_metrics.GetLogMetricRequest.serialize, + response_deserializer=logging_metrics.LogMetric.deserialize, + ) + return self._stubs["get_log_metric"] + + @property + def create_log_metric( + self, + ) -> Callable[ + [logging_metrics.CreateLogMetricRequest], Awaitable[logging_metrics.LogMetric] + ]: + r"""Return a callable for the create log metric method over gRPC. + + Creates a logs-based metric. + + Returns: + Callable[[~.CreateLogMetricRequest], + Awaitable[~.LogMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_log_metric" not in self._stubs: + self._stubs["create_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/CreateLogMetric", + request_serializer=logging_metrics.CreateLogMetricRequest.serialize, + response_deserializer=logging_metrics.LogMetric.deserialize, + ) + return self._stubs["create_log_metric"] + + @property + def update_log_metric( + self, + ) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], Awaitable[logging_metrics.LogMetric] + ]: + r"""Return a callable for the update log metric method over gRPC. + + Creates or updates a logs-based metric. + + Returns: + Callable[[~.UpdateLogMetricRequest], + Awaitable[~.LogMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_log_metric" not in self._stubs: + self._stubs["update_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", + request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, + response_deserializer=logging_metrics.LogMetric.deserialize, + ) + return self._stubs["update_log_metric"] + + @property + def delete_log_metric( + self, + ) -> Callable[[logging_metrics.DeleteLogMetricRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete log metric method over gRPC. + + Deletes a logs-based metric. + + Returns: + Callable[[~.DeleteLogMetricRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_log_metric" not in self._stubs: + self._stubs["delete_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", + request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_log_metric"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_log_metrics: self._wrap_method( + self.list_log_metrics, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_log_metric: self._wrap_method( + self.get_log_metric, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_log_metric: self._wrap_method( + self.create_log_metric, + default_timeout=60.0, + client_info=client_info, + ), + self.update_log_metric: self._wrap_method( + self.update_log_metric, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_log_metric: self._wrap_method( + self.delete_log_metric, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("MetricsServiceV2GrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/sink.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/sink.py new file mode 100644 index 0000000000000000000000000000000000000000..43dd2208cfc78e6db214e7b43dd61c972805e473 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/sink.py @@ -0,0 +1,233 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Define Cloud Logging API Sinks.""" + +from google.cloud.exceptions import NotFound + + +class Sink(object): + """Sinks represent filtered exports for log entries. + + See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks + """ + + def __init__( + self, name, *, filter_=None, parent=None, destination=None, client=None + ): + """ + Args: + name (str): The name of the sink. + parent(Optional[str]): The resource in which to create the sink: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + + Defaults to the project stored on the client. + filter_ (Optional[str]): The advanced logs filter expression defining + the entries exported by the sink. + destination (Optional[str]): Destination URI for the entries exported by the sink. + If not passed, the instance should already exist, to + be refreshed via :meth:`reload`. + client (Optional[~logging_v2.client.Client]): A client which holds + credentials and project configuration for the sink (which requires a project). + """ + self.name = name + self.filter_ = filter_ + self.destination = destination + self._client = client + self._parent = parent + self._writer_identity = None + + @property + def client(self): + """Client bound to the sink.""" + return self._client + + @property + def parent(self): + """Parent resource of the sink (project, organization, billingAccount, or folder).""" + if self._parent is None: + self._parent = f"projects/{self.client.project}" + return self._parent + + @property + def full_name(self): + """Fully-qualified name used in sink APIs""" + return f"{self.parent}/sinks/{self.name}" + + @property + def path(self): + """URL path for the sink's APIs""" + return f"/{self.full_name}" + + @property + def writer_identity(self): + """Identity used for exports via the sink""" + return self._writer_identity + + def _update_from_api_repr(self, resource): + """Helper for API methods returning sink resources.""" + self.destination = resource["destination"] + self.filter_ = resource.get("filter") + self._writer_identity = resource.get("writerIdentity") + + @classmethod + def from_api_repr(cls, resource, client, *, parent=None): + """Construct a sink given its API representation + + Args: + resource (dict): sink resource representation returned from the API + client (~logging_v2.client.Client): Client which holds + credentials and project configuration for the sink. + parent(Optional[str]): The resource in which to create the sink: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + + Defaults to the project stored on the client. + + Returns: + ~logging_v2.sink.Sink: Sink parsed from ``resource``. + + Raises: + ValueError: if ``client`` is not ``None`` and the + project from the resource does not agree with the project + from the client. + """ + sink_name = resource["name"] + instance = cls(sink_name, client=client, parent=parent) + instance._update_from_api_repr(resource) + return instance + + def _require_client(self, client): + """Check client or verify over-ride. Also sets ``parent``. + + Args: + client (Union[None, ~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + + Returns: + ~logging_v2.client.Client: The client passed in + or the currently bound client. + """ + if client is None: + client = self._client + return client + + def create(self, *, client=None, unique_writer_identity=False): + """Create the sink via a PUT request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + unique_writer_identity (Optional[bool]): Determines the kind of + IAM identity returned as writer_identity in the new sink. + """ + client = self._require_client(client) + resource = client.sinks_api.sink_create( + self.parent, + self.name, + self.filter_, + self.destination, + unique_writer_identity=unique_writer_identity, + ) + self._update_from_api_repr(resource) + + def exists(self, *, client=None): + """Test for the existence of the sink via a GET request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + + Returns: + bool: Boolean indicating existence of the sink. + """ + client = self._require_client(client) + + try: + client.sinks_api.sink_get(self.full_name) + except NotFound: + return False + else: + return True + + def reload(self, *, client=None): + """Sync local sink configuration via a GET request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + """ + client = self._require_client(client) + resource = client.sinks_api.sink_get(self.full_name) + self._update_from_api_repr(resource) + + def update(self, *, client=None, unique_writer_identity=False): + """Update sink configuration via a PUT request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + unique_writer_identity (Optional[bool]): Determines the kind of + IAM identity returned as writer_identity in the new sink. + """ + client = self._require_client(client) + resource = client.sinks_api.sink_update( + self.full_name, + self.filter_, + self.destination, + unique_writer_identity=unique_writer_identity, + ) + self._update_from_api_repr(resource) + + def delete(self, *, client=None): + """Delete a sink via a DELETE request + + See + https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/delete + + Args: + client (Optional[~logging_v2.client.Client]): + The client to use. If not passed, falls back to the + ``client`` stored on the current sink. + """ + client = self._require_client(client) + client.sinks_api.sink_delete(self.full_name) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8519243a0d2a3c818364e96412f8780e8992e3e6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/__init__.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .log_entry import ( + LogEntry, + LogEntryOperation, + LogEntrySourceLocation, + LogSplit, +) +from .logging import ( + DeleteLogRequest, + ListLogEntriesRequest, + ListLogEntriesResponse, + ListLogsRequest, + ListLogsResponse, + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + TailLogEntriesRequest, + TailLogEntriesResponse, + WriteLogEntriesPartialErrors, + WriteLogEntriesRequest, + WriteLogEntriesResponse, +) +from .logging_config import ( + BigQueryDataset, + BigQueryOptions, + BucketMetadata, + CmekSettings, + CopyLogEntriesMetadata, + CopyLogEntriesRequest, + CopyLogEntriesResponse, + CreateBucketRequest, + CreateExclusionRequest, + CreateLinkRequest, + CreateSinkRequest, + CreateViewRequest, + DeleteBucketRequest, + DeleteExclusionRequest, + DeleteLinkRequest, + DeleteSinkRequest, + DeleteViewRequest, + GetBucketRequest, + GetCmekSettingsRequest, + GetExclusionRequest, + GetLinkRequest, + GetSettingsRequest, + GetSinkRequest, + GetViewRequest, + IndexConfig, + IndexType, + LifecycleState, + Link, + LinkMetadata, + ListBucketsRequest, + ListBucketsResponse, + ListExclusionsRequest, + ListExclusionsResponse, + ListLinksRequest, + ListLinksResponse, + ListSinksRequest, + ListSinksResponse, + ListViewsRequest, + ListViewsResponse, + LocationMetadata, + LogBucket, + LogExclusion, + LogSink, + LogView, + OperationState, + Settings, + UndeleteBucketRequest, + UpdateBucketRequest, + UpdateCmekSettingsRequest, + UpdateExclusionRequest, + UpdateSettingsRequest, + UpdateSinkRequest, + UpdateViewRequest, +) +from .logging_metrics import ( + CreateLogMetricRequest, + DeleteLogMetricRequest, + GetLogMetricRequest, + ListLogMetricsRequest, + ListLogMetricsResponse, + LogMetric, + UpdateLogMetricRequest, +) + +__all__ = ( + "LogEntry", + "LogEntryOperation", + "LogEntrySourceLocation", + "LogSplit", + "DeleteLogRequest", + "ListLogEntriesRequest", + "ListLogEntriesResponse", + "ListLogsRequest", + "ListLogsResponse", + "ListMonitoredResourceDescriptorsRequest", + "ListMonitoredResourceDescriptorsResponse", + "TailLogEntriesRequest", + "TailLogEntriesResponse", + "WriteLogEntriesPartialErrors", + "WriteLogEntriesRequest", + "WriteLogEntriesResponse", + "BigQueryDataset", + "BigQueryOptions", + "BucketMetadata", + "CmekSettings", + "CopyLogEntriesMetadata", + "CopyLogEntriesRequest", + "CopyLogEntriesResponse", + "CreateBucketRequest", + "CreateExclusionRequest", + "CreateLinkRequest", + "CreateSinkRequest", + "CreateViewRequest", + "DeleteBucketRequest", + "DeleteExclusionRequest", + "DeleteLinkRequest", + "DeleteSinkRequest", + "DeleteViewRequest", + "GetBucketRequest", + "GetCmekSettingsRequest", + "GetExclusionRequest", + "GetLinkRequest", + "GetSettingsRequest", + "GetSinkRequest", + "GetViewRequest", + "IndexConfig", + "Link", + "LinkMetadata", + "ListBucketsRequest", + "ListBucketsResponse", + "ListExclusionsRequest", + "ListExclusionsResponse", + "ListLinksRequest", + "ListLinksResponse", + "ListSinksRequest", + "ListSinksResponse", + "ListViewsRequest", + "ListViewsResponse", + "LocationMetadata", + "LogBucket", + "LogExclusion", + "LogSink", + "LogView", + "Settings", + "UndeleteBucketRequest", + "UpdateBucketRequest", + "UpdateCmekSettingsRequest", + "UpdateExclusionRequest", + "UpdateSettingsRequest", + "UpdateSinkRequest", + "UpdateViewRequest", + "IndexType", + "LifecycleState", + "OperationState", + "CreateLogMetricRequest", + "DeleteLogMetricRequest", + "GetLogMetricRequest", + "ListLogMetricsRequest", + "ListLogMetricsResponse", + "LogMetric", + "UpdateLogMetricRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/log_entry.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/log_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..b381dd1eb9a707c77530137613671eaec5d985da --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/log_entry.py @@ -0,0 +1,433 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore +import google.logging.type.http_request_pb2 as http_request_pb2 # type: ignore +import google.logging.type.log_severity_pb2 as log_severity_pb2 # type: ignore +import google.protobuf.any_pb2 as any_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.logging.v2", + manifest={ + "LogEntry", + "LogEntryOperation", + "LogEntrySourceLocation", + "LogSplit", + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + log_name (str): + Required. The resource name of the log to which this log + entry belongs: + + :: + + "projects/[PROJECT_ID]/logs/[LOG_ID]" + "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + "folders/[FOLDER_ID]/logs/[LOG_ID]" + + A project number may be used in place of PROJECT_ID. The + project number is translated to its corresponding PROJECT_ID + internally and the ``log_name`` field will contain + PROJECT_ID in queries and exports. + + ``[LOG_ID]`` must be URL-encoded within ``log_name``. + Example: + ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. + + ``[LOG_ID]`` must be less than 512 characters long and can + only include the following characters: upper and lower case + alphanumeric characters, forward-slash, underscore, hyphen, + and period. + + For backward compatibility, if ``log_name`` begins with a + forward-slash, such as ``/projects/...``, then the log entry + is ingested as usual, but the forward-slash is removed. + Listing the log entry will not show the leading slash and + filtering for a log name with a leading slash will never + return any results. + resource (google.api.monitored_resource_pb2.MonitoredResource): + Required. The monitored resource that + produced this log entry. + Example: a log entry that reports a database + error would be associated with the monitored + resource designating the particular database + that reported the error. + proto_payload (google.protobuf.any_pb2.Any): + The log entry payload, represented as a + protocol buffer. Some Google Cloud Platform + services use this field for their log entry + payloads. + + The following protocol buffer types are + supported; user-defined types are not supported: + + "type.googleapis.com/google.cloud.audit.AuditLog" + "type.googleapis.com/google.appengine.logging.v1.RequestLog". + + This field is a member of `oneof`_ ``payload``. + text_payload (str): + The log entry payload, represented as a + Unicode string (UTF-8). + + This field is a member of `oneof`_ ``payload``. + json_payload (google.protobuf.struct_pb2.Struct): + The log entry payload, represented as a + structure that is expressed as a JSON object. + + This field is a member of `oneof`_ ``payload``. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time the event described by the log entry + occurred. This time is used to compute the log entry's age + and to enforce the logs retention period. If this field is + omitted in a new log entry, then Logging assigns it the + current time. Timestamps have nanosecond accuracy, but + trailing zeros in the fractional seconds might be omitted + when the timestamp is displayed. + + Incoming log entries must have timestamps that don't exceed + the `logs retention + period `__ + in the past, and that don't exceed 24 hours in the future. + Log entries outside those time boundaries aren't ingested by + Logging. + receive_timestamp (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the log entry was + received by Logging. + severity (google.logging.type.log_severity_pb2.LogSeverity): + Optional. The severity of the log entry. The default value + is ``LogSeverity.DEFAULT``. + insert_id (str): + Optional. A unique identifier for the log entry. If you + provide a value, then Logging considers other log entries in + the same project, with the same ``timestamp``, and with the + same ``insert_id`` to be duplicates which are removed in a + single query result. However, there are no guarantees of + de-duplication in the export of logs. + + If the ``insert_id`` is omitted when writing a log entry, + the Logging API assigns its own unique identifier in this + field. + + In queries, the ``insert_id`` is also used to order log + entries that have the same ``log_name`` and ``timestamp`` + values. + http_request (google.logging.type.http_request_pb2.HttpRequest): + Optional. Information about the HTTP request + associated with this log entry, if applicable. + labels (MutableMapping[str, str]): + Optional. A map of key, value pairs that provides additional + information about the log entry. The labels can be + user-defined or system-defined. + + User-defined labels are arbitrary key, value pairs that you + can use to classify logs. + + System-defined labels are defined by GCP services for + platform logs. They have two components - a service + namespace component and the attribute name. For example: + ``compute.googleapis.com/resource_name``. + + Cloud Logging truncates label keys that exceed 512 B and + label values that exceed 64 KB upon their associated log + entry being written. The truncation is indicated by an + ellipsis at the end of the character string. + operation (google.cloud.logging_v2.types.LogEntryOperation): + Optional. Information about an operation + associated with the log entry, if applicable. + trace (str): + Optional. The REST resource name of the trace being written + to `Cloud Trace `__ in + association with this log entry. For example, if your trace + data is stored in the Cloud project "my-trace-project" and + if the service that is creating the log entry receives a + trace header that includes the trace ID "12345", then the + service should use + "projects/my-tracing-project/traces/12345". + + The ``trace`` field provides the link between logs and + traces. By using this field, you can navigate from a log + entry to a trace. + span_id (str): + Optional. The ID of the `Cloud + Trace `__ span associated + with the current operation in which the log is being + written. For example, if a span has the REST resource name + of + "projects/some-project/traces/some-trace/spans/some-span-id", + then the ``span_id`` field is "some-span-id". + + A + `Span `__ + represents a single operation within a trace. Whereas a + trace may involve multiple different microservices running + on multiple different machines, a span generally corresponds + to a single logical operation being performed in a single + instance of a microservice on one specific machine. Spans + are the nodes within the tree that is a trace. + + Applications that are `instrumented for + tracing `__ will + generally assign a new, unique span ID on each incoming + request. It is also common to create and record additional + spans corresponding to internal processing elements as well + as issuing requests to dependencies. + + The span ID is expected to be a 16-character, hexadecimal + encoding of an 8-byte array and should not be zero. It + should be unique within the trace and should, ideally, be + generated in a manner that is uniformly random. + + Example values: + + - ``000000000000004a`` + - ``7a2190356c3fc94b`` + - ``0000f00300090021`` + - ``d39223e101960076`` + trace_sampled (bool): + Optional. The sampling decision of the trace associated with + the log entry. + + True means that the trace resource name in the ``trace`` + field was sampled for storage in a trace backend. False + means that the trace was not sampled for storage when this + log entry was written, or the sampling decision was unknown + at the time. A non-sampled ``trace`` value is still useful + as a request correlation identifier. The default is False. + source_location (google.cloud.logging_v2.types.LogEntrySourceLocation): + Optional. Source code location information + associated with the log entry, if any. + split (google.cloud.logging_v2.types.LogSplit): + Optional. Information indicating this + LogEntry is part of a sequence of multiple log + entries split from a single LogEntry. + """ + + log_name: str = proto.Field( + proto.STRING, + number=12, + ) + resource: monitored_resource_pb2.MonitoredResource = proto.Field( + proto.MESSAGE, + number=8, + message=monitored_resource_pb2.MonitoredResource, + ) + proto_payload: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=2, + oneof="payload", + message=any_pb2.Any, + ) + text_payload: str = proto.Field( + proto.STRING, + number=3, + oneof="payload", + ) + json_payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + oneof="payload", + message=struct_pb2.Struct, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + receive_timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=24, + message=timestamp_pb2.Timestamp, + ) + severity: log_severity_pb2.LogSeverity = proto.Field( + proto.ENUM, + number=10, + enum=log_severity_pb2.LogSeverity, + ) + insert_id: str = proto.Field( + proto.STRING, + number=4, + ) + http_request: http_request_pb2.HttpRequest = proto.Field( + proto.MESSAGE, + number=7, + message=http_request_pb2.HttpRequest, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + operation: "LogEntryOperation" = proto.Field( + proto.MESSAGE, + number=15, + message="LogEntryOperation", + ) + trace: str = proto.Field( + proto.STRING, + number=22, + ) + span_id: str = proto.Field( + proto.STRING, + number=27, + ) + trace_sampled: bool = proto.Field( + proto.BOOL, + number=30, + ) + source_location: "LogEntrySourceLocation" = proto.Field( + proto.MESSAGE, + number=23, + message="LogEntrySourceLocation", + ) + split: "LogSplit" = proto.Field( + proto.MESSAGE, + number=35, + message="LogSplit", + ) + + +class LogEntryOperation(proto.Message): + r"""Additional information about a potentially long-running + operation with which a log entry is associated. + + Attributes: + id (str): + Optional. An arbitrary operation identifier. + Log entries with the same identifier are assumed + to be part of the same operation. + producer (str): + Optional. An arbitrary producer identifier. The combination + of ``id`` and ``producer`` must be globally unique. Examples + for ``producer``: ``"MyDivision.MyBigCompany.com"``, + ``"github.com/MyProject/MyApplication"``. + first (bool): + Optional. Set this to True if this is the + first log entry in the operation. + last (bool): + Optional. Set this to True if this is the + last log entry in the operation. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + producer: str = proto.Field( + proto.STRING, + number=2, + ) + first: bool = proto.Field( + proto.BOOL, + number=3, + ) + last: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class LogEntrySourceLocation(proto.Message): + r"""Additional information about the source code location that + produced the log entry. + + Attributes: + file (str): + Optional. Source file name. Depending on the + runtime environment, this might be a simple name + or a fully-qualified name. + line (int): + Optional. Line within the source file. + 1-based; 0 indicates no line number available. + function (str): + Optional. Human-readable name of the function or method + being invoked, with optional context such as the class or + package name. This information may be used in contexts such + as the logs viewer, where a file and line number are less + meaningful. The format can vary by language. For example: + ``qual.if.ied.Class.method`` (Java), ``dir/package.func`` + (Go), ``function`` (Python). + """ + + file: str = proto.Field( + proto.STRING, + number=1, + ) + line: int = proto.Field( + proto.INT64, + number=2, + ) + function: str = proto.Field( + proto.STRING, + number=3, + ) + + +class LogSplit(proto.Message): + r"""Additional information used to correlate multiple log + entries. Used when a single LogEntry would exceed the Google + Cloud Logging size limit and is split across multiple log + entries. + + Attributes: + uid (str): + A globally unique identifier for all log entries in a + sequence of split log entries. All log entries with the same + \|LogSplit.uid\| are assumed to be part of the same sequence + of split log entries. + index (int): + The index of this LogEntry in the sequence of split log + entries. Log entries are given \|index\| values 0, 1, ..., + n-1 for a sequence of n log entries. + total_splits (int): + The total number of log entries that the + original LogEntry was split into. + """ + + uid: str = proto.Field( + proto.STRING, + number=1, + ) + index: int = proto.Field( + proto.INT32, + number=2, + ) + total_splits: int = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..a21e4d810197bfe1bcdb89039675a64775ac7eb0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging.py @@ -0,0 +1,602 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.logging_v2.types import log_entry + +__protobuf__ = proto.module( + package="google.logging.v2", + manifest={ + "DeleteLogRequest", + "WriteLogEntriesRequest", + "WriteLogEntriesResponse", + "WriteLogEntriesPartialErrors", + "ListLogEntriesRequest", + "ListLogEntriesResponse", + "ListMonitoredResourceDescriptorsRequest", + "ListMonitoredResourceDescriptorsResponse", + "ListLogsRequest", + "ListLogsResponse", + "TailLogEntriesRequest", + "TailLogEntriesResponse", + }, +) + + +class DeleteLogRequest(proto.Message): + r"""The parameters to DeleteLog. + + Attributes: + log_name (str): + Required. The resource name of the log to delete: + + - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` + - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` + - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` + + ``[LOG_ID]`` must be URL-encoded. For example, + ``"projects/my-project-id/logs/syslog"``, + ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``. + + For more information about log names, see + [LogEntry][google.logging.v2.LogEntry]. + """ + + log_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class WriteLogEntriesRequest(proto.Message): + r"""The parameters to WriteLogEntries. + + Attributes: + log_name (str): + Optional. A default log resource name that is assigned to + all log entries in ``entries`` that do not specify a value + for ``log_name``: + + - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` + - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` + - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` + + ``[LOG_ID]`` must be URL-encoded. For example: + + :: + + "projects/my-project-id/logs/syslog" + "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" + + The permission ``logging.logEntries.create`` is needed on + each project, organization, billing account, or folder that + is receiving new log entries, whether the resource is + specified in ``logName`` or in an individual log entry. + resource (google.api.monitored_resource_pb2.MonitoredResource): + Optional. A default monitored resource object that is + assigned to all log entries in ``entries`` that do not + specify a value for ``resource``. Example: + + :: + + { "type": "gce_instance", + "labels": { + "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + + See [LogEntry][google.logging.v2.LogEntry]. + labels (MutableMapping[str, str]): + Optional. Default labels that are added to the ``labels`` + field of all log entries in ``entries``. If a log entry + already has a label with the same key as a label in this + parameter, then the log entry's label is not changed. See + [LogEntry][google.logging.v2.LogEntry]. + entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]): + Required. The log entries to send to Logging. The order of + log entries in this list does not matter. Values supplied in + this method's ``log_name``, ``resource``, and ``labels`` + fields are copied into those log entries in this list that + do not include values for their corresponding fields. For + more information, see the + [LogEntry][google.logging.v2.LogEntry] type. + + If the ``timestamp`` or ``insert_id`` fields are missing in + log entries, then this method supplies the current time or a + unique identifier, respectively. The supplied values are + chosen so that, among the log entries that did not supply + their own values, the entries earlier in the list will sort + before the entries later in the list. See the + ``entries.list`` method. + + Log entries with timestamps that are more than the `logs + retention + period `__ in the + past or more than 24 hours in the future will not be + available when calling ``entries.list``. However, those log + entries can still be `exported with + LogSinks `__. + + To improve throughput and to avoid exceeding the `quota + limit `__ for calls + to ``entries.write``, you should try to include several log + entries in this list, rather than calling this method for + each individual log entry. + partial_success (bool): + Optional. Whether a batch's valid entries should be written + even if some other entry failed due to a permanent error + such as INVALID_ARGUMENT or PERMISSION_DENIED. If any entry + failed, then the response status is the response status of + one of the failed entries. The response will include error + details in ``WriteLogEntriesPartialErrors.log_entry_errors`` + keyed by the entries' zero-based index in the ``entries``. + Failed requests for which no entries are written will not + include per-entry errors. + dry_run (bool): + Optional. If true, the request should expect + normal response, but the entries won't be + persisted nor exported. Useful for checking + whether the logging API endpoints are working + properly before sending valuable data. + """ + + log_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: monitored_resource_pb2.MonitoredResource = proto.Field( + proto.MESSAGE, + number=2, + message=monitored_resource_pb2.MonitoredResource, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=log_entry.LogEntry, + ) + partial_success: bool = proto.Field( + proto.BOOL, + number=5, + ) + dry_run: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class WriteLogEntriesResponse(proto.Message): + r"""Result returned from WriteLogEntries.""" + + +class WriteLogEntriesPartialErrors(proto.Message): + r"""Error details for WriteLogEntries with partial success. + + Attributes: + log_entry_errors (MutableMapping[int, google.rpc.status_pb2.Status]): + When ``WriteLogEntriesRequest.partial_success`` is true, + records the error status for entries that were not written + due to a permanent error, keyed by the entry's zero-based + index in ``WriteLogEntriesRequest.entries``. + + Failed requests for which no entries are written will not + include per-entry errors. + """ + + log_entry_errors: MutableMapping[int, status_pb2.Status] = proto.MapField( + proto.INT32, + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +class ListLogEntriesRequest(proto.Message): + r"""The parameters to ``ListLogEntries``. + + Attributes: + resource_names (MutableSequence[str]): + Required. Names of one or more parent resources from which + to retrieve log entries: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + May alternatively be one or more views: + + - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + + Projects listed in the ``project_ids`` field are added to + this list. A maximum of 100 resources may be specified in a + single request. + filter (str): + Optional. Only log entries that match the filter are + returned. An empty filter matches all log entries in the + resources listed in ``resource_names``. Referencing a parent + resource that is not listed in ``resource_names`` will cause + the filter to return no results. The maximum length of a + filter is 20,000 characters. + order_by (str): + Optional. How the results should be sorted. Presently, the + only permitted values are ``"timestamp asc"`` (default) and + ``"timestamp desc"``. The first option returns entries in + order of increasing values of ``LogEntry.timestamp`` (oldest + first), and the second option returns entries in order of + decreasing timestamps (newest first). Entries with equal + timestamps are returned in order of their ``insert_id`` + values. + page_size (int): + Optional. The maximum number of results to return from this + request. Default is 50. If the value is negative or exceeds + 1000, the request is rejected. The presence of + ``next_page_token`` in the response indicates that more + results might be available. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``page_token`` must be the value of ``next_page_token`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + """ + + resource_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListLogEntriesResponse(proto.Message): + r"""Result returned from ``ListLogEntries``. + + Attributes: + entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]): + A list of log entries. If ``entries`` is empty, + ``nextPageToken`` may still be returned, indicating that + more entries may exist. See ``nextPageToken`` for more + information. + next_page_token (str): + If there might be more results than those appearing in this + response, then ``nextPageToken`` is included. To get the + next set of results, call this method again using the value + of ``nextPageToken`` as ``pageToken``. + + If a value for ``next_page_token`` appears and the + ``entries`` field is empty, it means that the search found + no log entries so far but it did not have time to search all + the possible log entries. Retry the method with this value + for ``page_token`` to continue the search. Alternatively, + consider speeding up the search by changing your filter to + specify a single log name or resource type, or to narrow the + time range of the search. + """ + + @property + def raw_page(self): + return self + + entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=log_entry.LogEntry, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListMonitoredResourceDescriptorsRequest(proto.Message): + r"""The parameters to ListMonitoredResourceDescriptors + + Attributes: + page_size (int): + Optional. The maximum number of results to return from this + request. Non-positive values are ignored. The presence of + ``nextPageToken`` in the response indicates that more + results might be available. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListMonitoredResourceDescriptorsResponse(proto.Message): + r"""Result returned from ListMonitoredResourceDescriptors. + + Attributes: + resource_descriptors (MutableSequence[google.api.monitored_resource_pb2.MonitoredResourceDescriptor]): + A list of resource descriptors. + next_page_token (str): + If there might be more results than those appearing in this + response, then ``nextPageToken`` is included. To get the + next set of results, call this method again using the value + of ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + resource_descriptors: MutableSequence[ + monitored_resource_pb2.MonitoredResourceDescriptor + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=monitored_resource_pb2.MonitoredResourceDescriptor, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListLogsRequest(proto.Message): + r"""The parameters to ListLogs. + + Attributes: + parent (str): + Required. The resource name to list logs for: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + resource_names (MutableSequence[str]): + Optional. List of resource names to list logs for: + + - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + + To support legacy queries, it could also be: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + The resource name in the ``parent`` field is added to this + list. + page_size (int): + Optional. The maximum number of results to return from this + request. Non-positive values are ignored. The presence of + ``nextPageToken`` in the response indicates that more + results might be available. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListLogsResponse(proto.Message): + r"""Result returned from ListLogs. + + Attributes: + log_names (MutableSequence[str]): + A list of log names. For example, + ``"projects/my-project/logs/syslog"`` or + ``"organizations/123/logs/cloudresourcemanager.googleapis.com%2Factivity"``. + next_page_token (str): + If there might be more results than those appearing in this + response, then ``nextPageToken`` is included. To get the + next set of results, call this method again using the value + of ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + log_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TailLogEntriesRequest(proto.Message): + r"""The parameters to ``TailLogEntries``. + + Attributes: + resource_names (MutableSequence[str]): + Required. Name of a parent resource from which to retrieve + log entries: + + - ``projects/[PROJECT_ID]`` + - ``organizations/[ORGANIZATION_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]`` + - ``folders/[FOLDER_ID]`` + + May alternatively be one or more views: + + - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` + filter (str): + Optional. Only log entries that match the filter are + returned. An empty filter matches all log entries in the + resources listed in ``resource_names``. Referencing a parent + resource that is not listed in ``resource_names`` will cause + the filter to return no results. The maximum length of a + filter is 20,000 characters. + buffer_window (google.protobuf.duration_pb2.Duration): + Optional. The amount of time to buffer log + entries at the server before being returned to + prevent out of order results due to late + arriving log entries. Valid values are between + 0-60000 milliseconds. Defaults to 2000 + milliseconds. + """ + + resource_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + buffer_window: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + +class TailLogEntriesResponse(proto.Message): + r"""Result returned from ``TailLogEntries``. + + Attributes: + entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]): + A list of log entries. Each response in the stream will + order entries with increasing values of + ``LogEntry.timestamp``. Ordering is not guaranteed between + separate responses. + suppression_info (MutableSequence[google.cloud.logging_v2.types.TailLogEntriesResponse.SuppressionInfo]): + If entries that otherwise would have been + included in the session were not sent back to + the client, counts of relevant entries omitted + from the session with the reason that they were + not included. There will be at most one of each + reason per response. The counts represent the + number of suppressed entries since the last + streamed response. + """ + + class SuppressionInfo(proto.Message): + r"""Information about entries that were omitted from the session. + + Attributes: + reason (google.cloud.logging_v2.types.TailLogEntriesResponse.SuppressionInfo.Reason): + The reason that entries were omitted from the + session. + suppressed_count (int): + A lower bound on the count of entries omitted due to + ``reason``. + """ + + class Reason(proto.Enum): + r"""An indicator of why entries were omitted. + + Values: + REASON_UNSPECIFIED (0): + Unexpected default. + RATE_LIMIT (1): + Indicates suppression occurred due to relevant entries being + received in excess of rate limits. For quotas and limits, + see `Logging API quotas and + limits `__. + NOT_CONSUMED (2): + Indicates suppression occurred due to the + client not consuming responses quickly enough. + """ + + REASON_UNSPECIFIED = 0 + RATE_LIMIT = 1 + NOT_CONSUMED = 2 + + reason: "TailLogEntriesResponse.SuppressionInfo.Reason" = proto.Field( + proto.ENUM, + number=1, + enum="TailLogEntriesResponse.SuppressionInfo.Reason", + ) + suppressed_count: int = proto.Field( + proto.INT32, + number=2, + ) + + entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=log_entry.LogEntry, + ) + suppression_info: MutableSequence[SuppressionInfo] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=SuppressionInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging_config.py new file mode 100644 index 0000000000000000000000000000000000000000..78792702a5dd15b3fe1b9f759e81d8c80d29cef2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging_config.py @@ -0,0 +1,2420 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.logging.v2", + manifest={ + "OperationState", + "LifecycleState", + "IndexType", + "IndexConfig", + "LogBucket", + "LogView", + "LogSink", + "BigQueryDataset", + "Link", + "BigQueryOptions", + "ListBucketsRequest", + "ListBucketsResponse", + "CreateBucketRequest", + "UpdateBucketRequest", + "GetBucketRequest", + "DeleteBucketRequest", + "UndeleteBucketRequest", + "ListViewsRequest", + "ListViewsResponse", + "CreateViewRequest", + "UpdateViewRequest", + "GetViewRequest", + "DeleteViewRequest", + "ListSinksRequest", + "ListSinksResponse", + "GetSinkRequest", + "CreateSinkRequest", + "UpdateSinkRequest", + "DeleteSinkRequest", + "CreateLinkRequest", + "DeleteLinkRequest", + "ListLinksRequest", + "ListLinksResponse", + "GetLinkRequest", + "LogExclusion", + "ListExclusionsRequest", + "ListExclusionsResponse", + "GetExclusionRequest", + "CreateExclusionRequest", + "UpdateExclusionRequest", + "DeleteExclusionRequest", + "GetCmekSettingsRequest", + "UpdateCmekSettingsRequest", + "CmekSettings", + "GetSettingsRequest", + "UpdateSettingsRequest", + "Settings", + "CopyLogEntriesRequest", + "CopyLogEntriesMetadata", + "CopyLogEntriesResponse", + "BucketMetadata", + "LinkMetadata", + "LocationMetadata", + }, +) + + +class OperationState(proto.Enum): + r"""List of different operation states. + High level state of the operation. This is used to report the + job's current state to the user. Once a long running operation + is created, the current state of the operation can be queried + even before the operation is finished and the final result is + available. + + Values: + OPERATION_STATE_UNSPECIFIED (0): + Should not be used. + OPERATION_STATE_SCHEDULED (1): + The operation is scheduled. + OPERATION_STATE_WAITING_FOR_PERMISSIONS (2): + Waiting for necessary permissions. + OPERATION_STATE_RUNNING (3): + The operation is running. + OPERATION_STATE_SUCCEEDED (4): + The operation was completed successfully. + OPERATION_STATE_FAILED (5): + The operation failed. + OPERATION_STATE_CANCELLED (6): + The operation was cancelled by the user. + """ + + OPERATION_STATE_UNSPECIFIED = 0 + OPERATION_STATE_SCHEDULED = 1 + OPERATION_STATE_WAITING_FOR_PERMISSIONS = 2 + OPERATION_STATE_RUNNING = 3 + OPERATION_STATE_SUCCEEDED = 4 + OPERATION_STATE_FAILED = 5 + OPERATION_STATE_CANCELLED = 6 + + +class LifecycleState(proto.Enum): + r"""LogBucket lifecycle states. + + Values: + LIFECYCLE_STATE_UNSPECIFIED (0): + Unspecified state. This is only used/useful + for distinguishing unset values. + ACTIVE (1): + The normal and active state. + DELETE_REQUESTED (2): + The resource has been marked for deletion by + the user. For some resources (e.g. buckets), + this can be reversed by an un-delete operation. + UPDATING (3): + The resource has been marked for an update by + the user. It will remain in this state until the + update is complete. + CREATING (4): + The resource has been marked for creation by + the user. It will remain in this state until the + creation is complete. + FAILED (5): + The resource is in an INTERNAL error state. + """ + + LIFECYCLE_STATE_UNSPECIFIED = 0 + ACTIVE = 1 + DELETE_REQUESTED = 2 + UPDATING = 3 + CREATING = 4 + FAILED = 5 + + +class IndexType(proto.Enum): + r"""IndexType is used for custom indexing. It describes the type + of an indexed field. + + Values: + INDEX_TYPE_UNSPECIFIED (0): + The index's type is unspecified. + INDEX_TYPE_STRING (1): + The index is a string-type index. + INDEX_TYPE_INTEGER (2): + The index is a integer-type index. + """ + + INDEX_TYPE_UNSPECIFIED = 0 + INDEX_TYPE_STRING = 1 + INDEX_TYPE_INTEGER = 2 + + +class IndexConfig(proto.Message): + r"""Configuration for an indexed field. + + Attributes: + field_path (str): + Required. The LogEntry field path to index. + + Note that some paths are automatically indexed, and other + paths are not eligible for indexing. See `indexing + documentation `__ + for details. + + For example: ``jsonPayload.request.status`` + type_ (google.cloud.logging_v2.types.IndexType): + Required. The type of data in this index. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the index was + last modified. + This is used to return the timestamp, and will + be ignored if supplied during update. + """ + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + type_: "IndexType" = proto.Field( + proto.ENUM, + number=2, + enum="IndexType", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class LogBucket(proto.Message): + r"""Describes a repository in which log entries are stored. + + Attributes: + name (str): + Output only. The resource name of the bucket. + + For example: + + ``projects/my-project/locations/global/buckets/my-bucket`` + + For a list of supported locations, see `Supported + Regions `__ + + For the location of ``global`` it is unspecified where log + entries are actually stored. + + After a bucket has been created, the location cannot be + changed. + description (str): + Describes this bucket. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation timestamp of the + bucket. This is not set for any of the default + buckets. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of the + bucket. + retention_days (int): + Logs will be retained by default for this + amount of time, after which they will + automatically be deleted. The minimum retention + period is 1 day. If this value is set to zero at + bucket creation time, the default time of 30 + days will be used. + locked (bool): + Whether the bucket is locked. + + The retention period on a locked bucket cannot + be changed. Locked buckets may only be deleted + if they are empty. + lifecycle_state (google.cloud.logging_v2.types.LifecycleState): + Output only. The bucket lifecycle state. + analytics_enabled (bool): + Whether log analytics is enabled for this + bucket. + Once enabled, log analytics features cannot be + disabled. + restricted_fields (MutableSequence[str]): + Log entry field paths that are denied access in this bucket. + + The following fields and their children are eligible: + ``textPayload``, ``jsonPayload``, ``protoPayload``, + ``httpRequest``, ``labels``, ``sourceLocation``. + + Restricting a repeated field will restrict all values. + Adding a parent will block all child fields. (e.g. + ``foo.bar`` will block ``foo.bar.baz``) + index_configs (MutableSequence[google.cloud.logging_v2.types.IndexConfig]): + A list of indexed fields and related + configuration data. + cmek_settings (google.cloud.logging_v2.types.CmekSettings): + The CMEK settings of the log bucket. If + present, new log entries written to this log + bucket are encrypted using the CMEK key provided + in this configuration. If a log bucket has CMEK + settings, the CMEK settings cannot be disabled + later by updating the log bucket. Changing the + KMS key is allowed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + retention_days: int = proto.Field( + proto.INT32, + number=11, + ) + locked: bool = proto.Field( + proto.BOOL, + number=9, + ) + lifecycle_state: "LifecycleState" = proto.Field( + proto.ENUM, + number=12, + enum="LifecycleState", + ) + analytics_enabled: bool = proto.Field( + proto.BOOL, + number=14, + ) + restricted_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + index_configs: MutableSequence["IndexConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="IndexConfig", + ) + cmek_settings: "CmekSettings" = proto.Field( + proto.MESSAGE, + number=19, + message="CmekSettings", + ) + + +class LogView(proto.Message): + r"""Describes a view over log entries in a bucket. + + Attributes: + name (str): + The resource name of the view. + + For example: + + ``projects/my-project/locations/global/buckets/my-bucket/views/my-view`` + description (str): + Describes this view. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation timestamp of the + view. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of the + view. + filter (str): + Filter that restricts which log entries in a bucket are + visible in this view. + + Filters are restricted to be a logical AND of ==/!= of any + of the following: + + - originating project/folder/organization/billing account. + - resource type + - log id + + For example: + + SOURCE("projects/myproject") AND resource.type = + "gce_instance" AND LOG_ID("stdout") + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + filter: str = proto.Field( + proto.STRING, + number=7, + ) + + +class LogSink(proto.Message): + r"""Describes a sink used to export log entries to one of the + following destinations in any project: a Cloud Storage bucket, a + BigQuery dataset, a Pub/Sub topic or a Cloud Logging log bucket. + A logs filter controls which log entries are exported. The sink + must be created within a project, organization, billing account, + or folder. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The client-assigned sink identifier, unique within + the project. + + For example: ``"my-syslog-errors-to-pubsub"``. Sink + identifiers are limited to 100 characters and can include + only the following characters: upper and lower-case + alphanumeric characters, underscores, hyphens, and periods. + First character has to be alphanumeric. + destination (str): + Required. The export destination: + + :: + + "storage.googleapis.com/[GCS_BUCKET]" + "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]" + "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]" + + The sink's ``writer_identity``, set when the sink is + created, must have permission to write to the destination or + else the log entries are not exported. For more information, + see `Exporting Logs with + Sinks `__. + filter (str): + Optional. An `advanced logs + filter `__. + The only exported log entries are those that are in the + resource owning the sink and that match the filter. + + For example: + + ``logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR`` + description (str): + Optional. A description of this sink. + + The maximum length of the description is 8000 + characters. + disabled (bool): + Optional. If set to true, then this sink is + disabled and it does not export any log entries. + exclusions (MutableSequence[google.cloud.logging_v2.types.LogExclusion]): + Optional. Log entries that match any of these exclusion + filters will not be exported. + + If a log entry is matched by both ``filter`` and one of + ``exclusion_filters`` it will not be exported. + output_version_format (google.cloud.logging_v2.types.LogSink.VersionFormat): + Deprecated. This field is unused. + writer_identity (str): + Output only. An IAM identity—a service account or + group—under which Cloud Logging writes the exported log + entries to the sink's destination. This field is either set + by specifying ``custom_writer_identity`` or set + automatically by + [sinks.create][google.logging.v2.ConfigServiceV2.CreateSink] + and + [sinks.update][google.logging.v2.ConfigServiceV2.UpdateSink] + based on the value of ``unique_writer_identity`` in those + methods. + + Until you grant this identity write-access to the + destination, log entry exports from this sink will fail. For + more information, see `Granting Access for a + Resource `__. + Consult the destination service's documentation to determine + the appropriate IAM roles to assign to the identity. + + Sinks that have a destination that is a log bucket in the + same project as the sink cannot have a writer_identity and + no additional permissions are required. + include_children (bool): + Optional. This field applies only to sinks owned by + organizations and folders. If the field is false, the + default, only the logs owned by the sink's parent resource + are available for export. If the field is true, then log + entries from all the projects, folders, and billing accounts + contained in the sink's parent resource are also available + for export. Whether a particular log entry from the children + is exported depends on the sink's filter expression. + + For example, if this field is true, then the filter + ``resource.type=gce_instance`` would export all Compute + Engine VM instance log entries from all projects in the + sink's parent. + + To only export entries from certain child projects, filter + on the project part of the log name: + + logName:("projects/test-project1/" OR + "projects/test-project2/") AND resource.type=gce_instance + bigquery_options (google.cloud.logging_v2.types.BigQueryOptions): + Optional. Options that affect sinks exporting + data to BigQuery. + + This field is a member of `oneof`_ ``options``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation timestamp of the + sink. + This field may not be present for older sinks. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of the + sink. + This field may not be present for older sinks. + """ + + class VersionFormat(proto.Enum): + r"""Deprecated. This is unused. + + Values: + VERSION_FORMAT_UNSPECIFIED (0): + An unspecified format version that will + default to V2. + V2 (1): + ``LogEntry`` version 2 format. + V1 (2): + ``LogEntry`` version 1 format. + """ + + VERSION_FORMAT_UNSPECIFIED = 0 + V2 = 1 + V1 = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + destination: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=18, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=19, + ) + exclusions: MutableSequence["LogExclusion"] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message="LogExclusion", + ) + output_version_format: VersionFormat = proto.Field( + proto.ENUM, + number=6, + enum=VersionFormat, + ) + writer_identity: str = proto.Field( + proto.STRING, + number=8, + ) + include_children: bool = proto.Field( + proto.BOOL, + number=9, + ) + bigquery_options: "BigQueryOptions" = proto.Field( + proto.MESSAGE, + number=12, + oneof="options", + message="BigQueryOptions", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=14, + message=timestamp_pb2.Timestamp, + ) + + +class BigQueryDataset(proto.Message): + r"""Describes a BigQuery dataset that was created by a link. + + Attributes: + dataset_id (str): + Output only. The full resource name of the BigQuery dataset. + The DATASET_ID will match the ID of the link, so the link + must match the naming restrictions of BigQuery datasets + (alphanumeric characters and underscores only). + + The dataset will have a resource path of + "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET_ID]". + """ + + dataset_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Link(proto.Message): + r"""Describes a link connected to an analytics enabled bucket. + + Attributes: + name (str): + The resource name of the link. The name can have up to 100 + characters. A valid link id (at the end of the link name) + must only have alphanumeric characters and underscores + within it. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + + For example: + + \`projects/my-project/locations/global/buckets/my-bucket/links/my_link + description (str): + Describes this link. + + The maximum length of the description is 8000 + characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation timestamp of the + link. + lifecycle_state (google.cloud.logging_v2.types.LifecycleState): + Output only. The resource lifecycle state. + bigquery_dataset (google.cloud.logging_v2.types.BigQueryDataset): + The information of a BigQuery Dataset. When a + link is created, a BigQuery dataset is created + along with it, in the same project as the + LogBucket it's linked to. This dataset will also + have BigQuery Views corresponding to the + LogViews in the bucket. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + lifecycle_state: "LifecycleState" = proto.Field( + proto.ENUM, + number=4, + enum="LifecycleState", + ) + bigquery_dataset: "BigQueryDataset" = proto.Field( + proto.MESSAGE, + number=5, + message="BigQueryDataset", + ) + + +class BigQueryOptions(proto.Message): + r"""Options that change functionality of a sink exporting data to + BigQuery. + + Attributes: + use_partitioned_tables (bool): + Optional. Whether to use `BigQuery's partition + tables `__. + By default, Cloud Logging creates dated tables based on the + log entries' timestamps, e.g. syslog_20170523. With + partitioned tables the date suffix is no longer present and + `special query + syntax `__ + has to be used instead. In both cases, tables are sharded + based on UTC timezone. + uses_timestamp_column_partitioning (bool): + Output only. True if new timestamp column based partitioning + is in use, false if legacy ingestion-time partitioning is in + use. + + All new sinks will have this field set true and will use + timestamp column based partitioning. If + use_partitioned_tables is false, this value has no meaning + and will be false. Legacy sinks using partitioned tables + will have this field set to false. + """ + + use_partitioned_tables: bool = proto.Field( + proto.BOOL, + number=1, + ) + uses_timestamp_column_partitioning: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListBucketsRequest(proto.Message): + r"""The parameters to ``ListBuckets``. + + Attributes: + parent (str): + Required. The parent resource whose buckets are to be + listed: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + + Note: The locations portion of the resource must be + specified, but supplying the character ``-`` in place of + [LOCATION_ID] will return all buckets. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + page_size (int): + Optional. The maximum number of results to return from this + request. Non-positive values are ignored. The presence of + ``nextPageToken`` in the response indicates that more + results might be available. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListBucketsResponse(proto.Message): + r"""The response from ListBuckets. + + Attributes: + buckets (MutableSequence[google.cloud.logging_v2.types.LogBucket]): + A list of buckets. + next_page_token (str): + If there might be more results than appear in this response, + then ``nextPageToken`` is included. To get the next set of + results, call the same method again using the value of + ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + buckets: MutableSequence["LogBucket"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LogBucket", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateBucketRequest(proto.Message): + r"""The parameters to ``CreateBucket``. + + Attributes: + parent (str): + Required. The resource in which to create the log bucket: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + + For example: + + ``"projects/my-project/locations/global"`` + bucket_id (str): + Required. A client-assigned identifier such as + ``"my-bucket"``. Identifiers are limited to 100 characters + and can include only letters, digits, underscores, hyphens, + and periods. + bucket (google.cloud.logging_v2.types.LogBucket): + Required. The new bucket. The region + specified in the new bucket must be compliant + with any Location Restriction Org Policy. The + name field in the bucket is ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + bucket_id: str = proto.Field( + proto.STRING, + number=2, + ) + bucket: "LogBucket" = proto.Field( + proto.MESSAGE, + number=3, + message="LogBucket", + ) + + +class UpdateBucketRequest(proto.Message): + r"""The parameters to ``UpdateBucket``. + + Attributes: + name (str): + Required. The full resource name of the bucket to update. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket"`` + bucket (google.cloud.logging_v2.types.LogBucket): + Required. The updated bucket. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask that specifies the fields in ``bucket`` + that need an update. A bucket field will be overwritten if, + and only if, it is in the update mask. ``name`` and output + only fields cannot be updated. + + For a detailed ``FieldMask`` definition, see: + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + + For example: ``updateMask=retention_days`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + bucket: "LogBucket" = proto.Field( + proto.MESSAGE, + number=2, + message="LogBucket", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class GetBucketRequest(proto.Message): + r"""The parameters to ``GetBucket``. + + Attributes: + name (str): + Required. The resource name of the bucket: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket"`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteBucketRequest(proto.Message): + r"""The parameters to ``DeleteBucket``. + + Attributes: + name (str): + Required. The full resource name of the bucket to delete. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket"`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteBucketRequest(proto.Message): + r"""The parameters to ``UndeleteBucket``. + + Attributes: + name (str): + Required. The full resource name of the bucket to undelete. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket"`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListViewsRequest(proto.Message): + r"""The parameters to ``ListViews``. + + Attributes: + parent (str): + Required. The bucket whose views are to be listed: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]". + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + page_size (int): + Optional. The maximum number of results to return from this + request. + + Non-positive values are ignored. The presence of + ``nextPageToken`` in the response indicates that more + results might be available. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListViewsResponse(proto.Message): + r"""The response from ListViews. + + Attributes: + views (MutableSequence[google.cloud.logging_v2.types.LogView]): + A list of views. + next_page_token (str): + If there might be more results than appear in this response, + then ``nextPageToken`` is included. To get the next set of + results, call the same method again using the value of + ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + views: MutableSequence["LogView"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LogView", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateViewRequest(proto.Message): + r"""The parameters to ``CreateView``. + + Attributes: + parent (str): + Required. The bucket in which to create the view + + :: + + `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket"`` + view_id (str): + Required. A client-assigned identifier such as + ``"my-view"``. Identifiers are limited to 100 characters and + can include only letters, digits, underscores, hyphens, and + periods. + view (google.cloud.logging_v2.types.LogView): + Required. The new view. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + view_id: str = proto.Field( + proto.STRING, + number=2, + ) + view: "LogView" = proto.Field( + proto.MESSAGE, + number=3, + message="LogView", + ) + + +class UpdateViewRequest(proto.Message): + r"""The parameters to ``UpdateView``. + + Attributes: + name (str): + Required. The full resource name of the view to update + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket/views/my-view"`` + view (google.cloud.logging_v2.types.LogView): + Required. The updated view. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that specifies the fields in ``view`` + that need an update. A field will be overwritten if, and + only if, it is in the update mask. ``name`` and output only + fields cannot be updated. + + For a detailed ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + + For example: ``updateMask=filter`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "LogView" = proto.Field( + proto.MESSAGE, + number=2, + message="LogView", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class GetViewRequest(proto.Message): + r"""The parameters to ``GetView``. + + Attributes: + name (str): + Required. The resource name of the policy: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + + For example: + + ``"projects/my-project/locations/global/buckets/my-bucket/views/my-view"`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteViewRequest(proto.Message): + r"""The parameters to ``DeleteView``. + + Attributes: + name (str): + Required. The full resource name of the view to delete: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + + For example: + + :: + + `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSinksRequest(proto.Message): + r"""The parameters to ``ListSinks``. + + Attributes: + parent (str): + Required. The parent resource whose sinks are to be listed: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]". + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + page_size (int): + Optional. The maximum number of results to return from this + request. Non-positive values are ignored. The presence of + ``nextPageToken`` in the response indicates that more + results might be available. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListSinksResponse(proto.Message): + r"""Result returned from ``ListSinks``. + + Attributes: + sinks (MutableSequence[google.cloud.logging_v2.types.LogSink]): + A list of sinks. + next_page_token (str): + If there might be more results than appear in this response, + then ``nextPageToken`` is included. To get the next set of + results, call the same method again using the value of + ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + sinks: MutableSequence["LogSink"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LogSink", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSinkRequest(proto.Message): + r"""The parameters to ``GetSink``. + + Attributes: + sink_name (str): + Required. The resource name of the sink: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + """ + + sink_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSinkRequest(proto.Message): + r"""The parameters to ``CreateSink``. + + Attributes: + parent (str): + Required. The resource in which to create the sink: + + :: + + "projects/[PROJECT_ID]" + "organizations/[ORGANIZATION_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]" + "folders/[FOLDER_ID]" + + For examples: + + ``"projects/my-project"`` ``"organizations/123456789"`` + sink (google.cloud.logging_v2.types.LogSink): + Required. The new sink, whose ``name`` parameter is a sink + identifier that is not already in use. + unique_writer_identity (bool): + Optional. Determines the kind of IAM identity returned as + ``writer_identity`` in the new sink. If this value is + omitted or set to false, and if the sink's parent is a + project, then the value returned as ``writer_identity`` is + the same group or service account used by Cloud Logging + before the addition of writer identities to this API. The + sink's destination must be in the same project as the sink + itself. + + If this field is set to true, or if the sink is owned by a + non-project resource such as an organization, then the value + of ``writer_identity`` will be a unique service account used + only for exports from the new sink. For more information, + see ``writer_identity`` in + [LogSink][google.logging.v2.LogSink]. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sink: "LogSink" = proto.Field( + proto.MESSAGE, + number=2, + message="LogSink", + ) + unique_writer_identity: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class UpdateSinkRequest(proto.Message): + r"""The parameters to ``UpdateSink``. + + Attributes: + sink_name (str): + Required. The full resource name of the sink to update, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + sink (google.cloud.logging_v2.types.LogSink): + Required. The updated sink, whose name is the same + identifier that appears as part of ``sink_name``. + unique_writer_identity (bool): + Optional. See + [sinks.create][google.logging.v2.ConfigServiceV2.CreateSink] + for a description of this field. When updating a sink, the + effect of this field on the value of ``writer_identity`` in + the updated sink depends on both the old and new values of + this field: + + - If the old and new values of this field are both false or + both true, then there is no change to the sink's + ``writer_identity``. + - If the old value is false and the new value is true, then + ``writer_identity`` is changed to a unique service + account. + - It is an error if the old value is true and the new value + is set to false or defaulted to false. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that specifies the fields in ``sink`` + that need an update. A sink field will be overwritten if, + and only if, it is in the update mask. ``name`` and output + only fields cannot be updated. + + An empty ``updateMask`` is temporarily treated as using the + following mask for backwards compatibility purposes: + + ``destination,filter,includeChildren`` + + At some point in the future, behavior will be removed and + specifying an empty ``updateMask`` will be an error. + + For a detailed ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + + For example: ``updateMask=filter`` + """ + + sink_name: str = proto.Field( + proto.STRING, + number=1, + ) + sink: "LogSink" = proto.Field( + proto.MESSAGE, + number=2, + message="LogSink", + ) + unique_writer_identity: bool = proto.Field( + proto.BOOL, + number=3, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSinkRequest(proto.Message): + r"""The parameters to ``DeleteSink``. + + Attributes: + sink_name (str): + Required. The full resource name of the sink to delete, + including the parent resource and the sink identifier: + + :: + + "projects/[PROJECT_ID]/sinks/[SINK_ID]" + "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + "folders/[FOLDER_ID]/sinks/[SINK_ID]" + + For example: + + ``"projects/my-project/sinks/my-sink"`` + """ + + sink_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateLinkRequest(proto.Message): + r"""The parameters to CreateLink. + + Attributes: + parent (str): + Required. The full resource name of the bucket to create a + link for. + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]". + link (google.cloud.logging_v2.types.Link): + Required. The new link. + link_id (str): + Required. The ID to use for the link. The link_id can have + up to 100 characters. A valid link_id must only have + alphanumeric characters and underscores within it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + link: "Link" = proto.Field( + proto.MESSAGE, + number=2, + message="Link", + ) + link_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteLinkRequest(proto.Message): + r"""The parameters to DeleteLink. + + Attributes: + name (str): + Required. The full resource name of the link to delete. + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListLinksRequest(proto.Message): + r"""The parameters to ListLinks. + + Attributes: + parent (str): + Required. The parent resource whose links are to be listed: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/ + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. + page_size (int): + Optional. The maximum number of results to + return from this request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListLinksResponse(proto.Message): + r"""The response from ListLinks. + + Attributes: + links (MutableSequence[google.cloud.logging_v2.types.Link]): + A list of links. + next_page_token (str): + If there might be more results than those appearing in this + response, then ``nextPageToken`` is included. To get the + next set of results, call the same method again using the + value of ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + links: MutableSequence["Link"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Link", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetLinkRequest(proto.Message): + r"""The parameters to GetLink. + + Attributes: + name (str): + Required. The resource name of the link: + + "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID]" + "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/links/[LINK_ID] + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class LogExclusion(proto.Message): + r"""Specifies a set of log entries that are filtered out by a sink. If + your Google Cloud resource receives a large volume of log entries, + you can use exclusions to reduce your chargeable logs. Note that + exclusions on organization-level and folder-level sinks don't apply + to child resources. Note also that you cannot modify the \_Required + sink or exclude logs from it. + + Attributes: + name (str): + Required. A client-assigned identifier, such as + ``"load-balancer-exclusion"``. Identifiers are limited to + 100 characters and can include only letters, digits, + underscores, hyphens, and periods. First character has to be + alphanumeric. + description (str): + Optional. A description of this exclusion. + filter (str): + Required. An `advanced logs + filter `__ + that matches the log entries to be excluded. By using the + `sample + function `__, + you can exclude less than 100% of the matching log entries. + + For example, the following query matches 99% of low-severity + log entries from Google Cloud Storage buckets: + + ``resource.type=gcs_bucket severity`__ + for more information. + + Attributes: + name (str): + Required. The resource for which to retrieve CMEK settings. + + :: + + "projects/[PROJECT_ID]/cmekSettings" + "organizations/[ORGANIZATION_ID]/cmekSettings" + "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" + "folders/[FOLDER_ID]/cmekSettings" + + For example: + + ``"organizations/12345/cmekSettings"`` + + Note: CMEK for the Log Router can be configured for Google + Cloud projects, folders, organizations and billing accounts. + Once configured for an organization, it applies to all + projects and folders in the Google Cloud organization. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCmekSettingsRequest(proto.Message): + r"""The parameters to + [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Attributes: + name (str): + Required. The resource name for the CMEK settings to update. + + :: + + "projects/[PROJECT_ID]/cmekSettings" + "organizations/[ORGANIZATION_ID]/cmekSettings" + "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" + "folders/[FOLDER_ID]/cmekSettings" + + For example: + + ``"organizations/12345/cmekSettings"`` + + Note: CMEK for the Log Router can currently only be + configured for Google Cloud organizations. Once configured, + it applies to all projects and folders in the Google Cloud + organization. + cmek_settings (google.cloud.logging_v2.types.CmekSettings): + Required. The CMEK settings to update. + + See `Enabling CMEK for Log + Router `__ + for more information. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask identifying which fields from + ``cmek_settings`` should be updated. A field will be + overwritten if and only if it is in the update mask. Output + only fields cannot be updated. + + See [FieldMask][google.protobuf.FieldMask] for more + information. + + For example: ``"updateMask=kmsKeyName"`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + cmek_settings: "CmekSettings" = proto.Field( + proto.MESSAGE, + number=2, + message="CmekSettings", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class CmekSettings(proto.Message): + r"""Describes the customer-managed encryption key (CMEK) settings + associated with a project, folder, organization, billing account, or + flexible resource. + + Note: CMEK for the Log Router can currently only be configured for + Google Cloud organizations. Once configured, it applies to all + projects and folders in the Google Cloud organization. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Attributes: + name (str): + Output only. The resource name of the CMEK + settings. + kms_key_name (str): + The resource name for the configured Cloud KMS key. + + KMS key name format: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]" + + For example: + + ``"projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key"`` + + To enable CMEK for the Log Router, set this field to a valid + ``kms_key_name`` for which the associated service account + has the required cloudkms.cryptoKeyEncrypterDecrypter roles + assigned for the key. + + The Cloud KMS key used by the Log Router can be updated by + changing the ``kms_key_name`` to a new valid key name or + disabled by setting the key name to an empty string. + Encryption operations that are in progress will be completed + with the key that was in use when they started. Decryption + operations will be completed using the key that was used at + the time of encryption unless access to that key has been + revoked. + + To disable CMEK for the Log Router, set this field to an + empty string. + + See `Enabling CMEK for Log + Router `__ + for more information. + kms_key_version_name (str): + The CryptoKeyVersion resource name for the configured Cloud + KMS key. + + KMS key name format: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]/cryptoKeyVersions/[VERSION]" + + For example: + + ``"projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key/cryptoKeyVersions/1"`` + + This is a read-only field used to convey the specific + configured CryptoKeyVersion of ``kms_key`` that has been + configured. It will be populated in cases where the CMEK + settings are bound to a single key version. + + If this field is populated, the ``kms_key`` is tied to a + specific CryptoKeyVersion. + service_account_id (str): + Output only. The service account that will be used by the + Log Router to access your Cloud KMS key. + + Before enabling CMEK for Log Router, you must first assign + the cloudkms.cryptoKeyEncrypterDecrypter role to the service + account that the Log Router will use to access your Cloud + KMS key. Use + [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings] + to obtain the service account ID. + + See `Enabling CMEK for Log + Router `__ + for more information. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=2, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=4, + ) + service_account_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetSettingsRequest(proto.Message): + r"""The parameters to + [GetSettings][google.logging.v2.ConfigServiceV2.GetSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Attributes: + name (str): + Required. The resource for which to retrieve settings. + + :: + + "projects/[PROJECT_ID]/settings" + "organizations/[ORGANIZATION_ID]/settings" + "billingAccounts/[BILLING_ACCOUNT_ID]/settings" + "folders/[FOLDER_ID]/settings" + + For example: + + ``"organizations/12345/settings"`` + + Note: Settings for the Log Router can be get for Google + Cloud projects, folders, organizations and billing accounts. + Currently it can only be configured for organizations. Once + configured for an organization, it applies to all projects + and folders in the Google Cloud organization. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSettingsRequest(proto.Message): + r"""The parameters to + [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings]. + + See `Enabling CMEK for Log + Router `__ + for more information. + + Attributes: + name (str): + Required. The resource name for the settings to update. + + :: + + "organizations/[ORGANIZATION_ID]/settings" + + For example: + + ``"organizations/12345/settings"`` + + Note: Settings for the Log Router can currently only be + configured for Google Cloud organizations. Once configured, + it applies to all projects and folders in the Google Cloud + organization. + settings (google.cloud.logging_v2.types.Settings): + Required. The settings to update. + + See `Enabling CMEK for Log + Router `__ + for more information. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask identifying which fields from + ``settings`` should be updated. A field will be overwritten + if and only if it is in the update mask. Output only fields + cannot be updated. + + See [FieldMask][google.protobuf.FieldMask] for more + information. + + For example: ``"updateMask=kmsKeyName"`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + settings: "Settings" = proto.Field( + proto.MESSAGE, + number=2, + message="Settings", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class Settings(proto.Message): + r"""Describes the settings associated with a project, folder, + organization, billing account, or flexible resource. + + Attributes: + name (str): + Output only. The resource name of the + settings. + kms_key_name (str): + Optional. The resource name for the configured Cloud KMS + key. + + KMS key name format: + + :: + + "projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]" + + For example: + + ``"projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key"`` + + To enable CMEK for the Log Router, set this field to a valid + ``kms_key_name`` for which the associated service account + has the required + ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned + for the key. + + The Cloud KMS key used by the Log Router can be updated by + changing the ``kms_key_name`` to a new valid key name. + Encryption operations that are in progress will be completed + with the key that was in use when they started. Decryption + operations will be completed using the key that was used at + the time of encryption unless access to that key has been + revoked. + + To disable CMEK for the Log Router, set this field to an + empty string. + + See `Enabling CMEK for Log + Router `__ + for more information. + kms_service_account_id (str): + Output only. The service account that will be used by the + Log Router to access your Cloud KMS key. + + Before enabling CMEK for Log Router, you must first assign + the role ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` to + the service account that the Log Router will use to access + your Cloud KMS key. Use + [GetSettings][google.logging.v2.ConfigServiceV2.GetSettings] + to obtain the service account ID. + + See `Enabling CMEK for Log + Router `__ + for more information. + storage_location (str): + Optional. The Cloud region that will be used for \_Default + and \_Required log buckets for newly created projects and + folders. For example ``europe-west1``. This setting does not + affect the location of custom log buckets. + disable_default_sink (bool): + Optional. If set to true, the \_Default sink in newly + created projects and folders will created in a disabled + state. This can be used to automatically disable log + ingestion if there is already an aggregated sink configured + in the hierarchy. The \_Default sink can be re-enabled + manually if needed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=2, + ) + kms_service_account_id: str = proto.Field( + proto.STRING, + number=3, + ) + storage_location: str = proto.Field( + proto.STRING, + number=4, + ) + disable_default_sink: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CopyLogEntriesRequest(proto.Message): + r"""The parameters to CopyLogEntries. + + Attributes: + name (str): + Required. Log bucket from which to copy log entries. + + For example: + + ``"projects/my-project/locations/global/buckets/my-source-bucket"`` + filter (str): + Optional. A filter specifying which log + entries to copy. The filter must be no more than + 20k characters. An empty filter matches all log + entries. + destination (str): + Required. Destination to which to copy log + entries. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + destination: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CopyLogEntriesMetadata(proto.Message): + r"""Metadata for CopyLogEntries long running operations. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The create time of an operation. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The end time of an operation. + state (google.cloud.logging_v2.types.OperationState): + State of an operation. + cancellation_requested (bool): + Identifies whether the user has requested + cancellation of the operation. + request (google.cloud.logging_v2.types.CopyLogEntriesRequest): + CopyLogEntries RPC request. + progress (int): + Estimated progress of the operation (0 - + 100%). + writer_identity (str): + The IAM identity of a service account that must be granted + access to the destination. + + If the service account is not granted permission to the + destination within an hour, the operation will be cancelled. + + For example: ``"serviceAccount:foo@bar.com"`` + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + state: "OperationState" = proto.Field( + proto.ENUM, + number=3, + enum="OperationState", + ) + cancellation_requested: bool = proto.Field( + proto.BOOL, + number=4, + ) + request: "CopyLogEntriesRequest" = proto.Field( + proto.MESSAGE, + number=5, + message="CopyLogEntriesRequest", + ) + progress: int = proto.Field( + proto.INT32, + number=6, + ) + writer_identity: str = proto.Field( + proto.STRING, + number=7, + ) + + +class CopyLogEntriesResponse(proto.Message): + r"""Response type for CopyLogEntries long running operations. + + Attributes: + log_entries_copied_count (int): + Number of log entries copied. + """ + + log_entries_copied_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class BucketMetadata(proto.Message): + r"""Metadata for LongRunningUpdateBucket Operations. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The create time of an operation. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The end time of an operation. + state (google.cloud.logging_v2.types.OperationState): + State of an operation. + create_bucket_request (google.cloud.logging_v2.types.CreateBucketRequest): + LongRunningCreateBucket RPC request. + + This field is a member of `oneof`_ ``request``. + update_bucket_request (google.cloud.logging_v2.types.UpdateBucketRequest): + LongRunningUpdateBucket RPC request. + + This field is a member of `oneof`_ ``request``. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + state: "OperationState" = proto.Field( + proto.ENUM, + number=3, + enum="OperationState", + ) + create_bucket_request: "CreateBucketRequest" = proto.Field( + proto.MESSAGE, + number=4, + oneof="request", + message="CreateBucketRequest", + ) + update_bucket_request: "UpdateBucketRequest" = proto.Field( + proto.MESSAGE, + number=5, + oneof="request", + message="UpdateBucketRequest", + ) + + +class LinkMetadata(proto.Message): + r"""Metadata for long running Link operations. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of an operation. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The end time of an operation. + state (google.cloud.logging_v2.types.OperationState): + State of an operation. + create_link_request (google.cloud.logging_v2.types.CreateLinkRequest): + CreateLink RPC request. + + This field is a member of `oneof`_ ``request``. + delete_link_request (google.cloud.logging_v2.types.DeleteLinkRequest): + DeleteLink RPC request. + + This field is a member of `oneof`_ ``request``. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + state: "OperationState" = proto.Field( + proto.ENUM, + number=3, + enum="OperationState", + ) + create_link_request: "CreateLinkRequest" = proto.Field( + proto.MESSAGE, + number=4, + oneof="request", + message="CreateLinkRequest", + ) + delete_link_request: "DeleteLinkRequest" = proto.Field( + proto.MESSAGE, + number=5, + oneof="request", + message="DeleteLinkRequest", + ) + + +class LocationMetadata(proto.Message): + r"""Cloud Logging specific location metadata. + + Attributes: + log_analytics_enabled (bool): + Indicates whether or not Log Analytics + features are supported in the given location. + """ + + log_analytics_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging_metrics.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe0393c0e838abd6fdbba5c5b3ffb3d7dc5c3ad --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/logging_v2/types/logging_metrics.py @@ -0,0 +1,411 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.api.distribution_pb2 as distribution_pb2 # type: ignore +import google.api.metric_pb2 as metric_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.logging.v2", + manifest={ + "LogMetric", + "ListLogMetricsRequest", + "ListLogMetricsResponse", + "GetLogMetricRequest", + "CreateLogMetricRequest", + "UpdateLogMetricRequest", + "DeleteLogMetricRequest", + }, +) + + +class LogMetric(proto.Message): + r"""Describes a logs-based metric. The value of the metric is the + number of log entries that match a logs filter in a given time + interval. + + Logs-based metrics can also be used to extract values from logs + and create a distribution of the values. The distribution + records the statistics of the extracted values along with an + optional histogram of the values as specified by the bucket + options. + + Attributes: + name (str): + Required. The client-assigned metric identifier. Examples: + ``"error_count"``, ``"nginx/requests"``. + + Metric identifiers are limited to 100 characters and can + include only the following characters: ``A-Z``, ``a-z``, + ``0-9``, and the special characters ``_-.,+!*',()%/``. The + forward-slash character (``/``) denotes a hierarchy of name + pieces, and it cannot be the first character of the name. + + This field is the ``[METRIC_ID]`` part of a metric resource + name in the format + "projects/[PROJECT_ID]/metrics/[METRIC_ID]". Example: If the + resource name of a metric is + ``"projects/my-project/metrics/nginx%2Frequests"``, this + field's value is ``"nginx/requests"``. + description (str): + Optional. A description of this metric, which + is used in documentation. The maximum length of + the description is 8000 characters. + filter (str): + Required. An `advanced logs + filter `__ + which is used to match log entries. Example: + + :: + + "resource.type=gae_app AND severity>=ERROR" + + The maximum length of the filter is 20000 characters. + bucket_name (str): + Optional. The resource name of the Log Bucket that owns the + Log Metric. Only Log Buckets in projects are supported. The + bucket has to be in the same project as the metric. + + For example: + + ``projects/my-project/locations/global/buckets/my-bucket`` + + If empty, then the Log Metric is considered a non-Bucket Log + Metric. + disabled (bool): + Optional. If set to True, then this metric is + disabled and it does not generate any points. + metric_descriptor (google.api.metric_pb2.MetricDescriptor): + Optional. The metric descriptor associated with the + logs-based metric. If unspecified, it uses a default metric + descriptor with a DELTA metric kind, INT64 value type, with + no labels and a unit of "1". Such a metric counts the number + of log entries matching the ``filter`` expression. + + The ``name``, ``type``, and ``description`` fields in the + ``metric_descriptor`` are output only, and is constructed + using the ``name`` and ``description`` field in the + LogMetric. + + To create a logs-based metric that records a distribution of + log values, a DELTA metric kind with a DISTRIBUTION value + type must be used along with a ``value_extractor`` + expression in the LogMetric. + + Each label in the metric descriptor must have a matching + label name as the key and an extractor expression as the + value in the ``label_extractors`` map. + + The ``metric_kind`` and ``value_type`` fields in the + ``metric_descriptor`` cannot be updated once initially + configured. New labels can be added in the + ``metric_descriptor``, but existing labels cannot be + modified except for their description. + value_extractor (str): + Optional. A ``value_extractor`` is required when using a + distribution logs-based metric to extract the values to + record from a log entry. Two functions are supported for + value extraction: ``EXTRACT(field)`` or + ``REGEXP_EXTRACT(field, regex)``. The arguments are: + + 1. field: The name of the log entry field from which the + value is to be extracted. + 2. regex: A regular expression using the Google RE2 syntax + (https://github.com/google/re2/wiki/Syntax) with a single + capture group to extract data from the specified log + entry field. The value of the field is converted to a + string before applying the regex. It is an error to + specify a regex that does not include exactly one capture + group. + + The result of the extraction must be convertible to a double + type, as the distribution always records double values. If + either the extraction or the conversion to double fails, + then those values are not recorded in the distribution. + + Example: + ``REGEXP_EXTRACT(jsonPayload.request, ".*quantity=(\d+).*")`` + label_extractors (MutableMapping[str, str]): + Optional. A map from a label key string to an extractor + expression which is used to extract data from a log entry + field and assign as the label value. Each label key + specified in the LabelDescriptor must have an associated + extractor expression in this map. The syntax of the + extractor expression is the same as for the + ``value_extractor`` field. + + The extracted value is converted to the type defined in the + label descriptor. If either the extraction or the type + conversion fails, the label will have a default value. The + default value for a string label is an empty string, for an + integer label its 0, and for a boolean label its ``false``. + + Note that there are upper bounds on the maximum number of + labels and the number of active time series that are allowed + in a project. + bucket_options (google.api.distribution_pb2.BucketOptions): + Optional. The ``bucket_options`` are required when the + logs-based metric is using a DISTRIBUTION value type and it + describes the bucket boundaries used to create a histogram + of the extracted values. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation timestamp of the + metric. + This field may not be present for older metrics. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of the + metric. + This field may not be present for older metrics. + version (google.cloud.logging_v2.types.LogMetric.ApiVersion): + Deprecated. The API version that created or + updated this metric. The v2 format is used by + default and cannot be changed. + """ + + class ApiVersion(proto.Enum): + r"""Logging API version. + + Values: + V2 (0): + Logging API v2. + V1 (1): + Logging API v1. + """ + + V2 = 0 + V1 = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + bucket_name: str = proto.Field( + proto.STRING, + number=13, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=12, + ) + metric_descriptor: metric_pb2.MetricDescriptor = proto.Field( + proto.MESSAGE, + number=5, + message=metric_pb2.MetricDescriptor, + ) + value_extractor: str = proto.Field( + proto.STRING, + number=6, + ) + label_extractors: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + bucket_options: distribution_pb2.Distribution.BucketOptions = proto.Field( + proto.MESSAGE, + number=8, + message=distribution_pb2.Distribution.BucketOptions, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + version: ApiVersion = proto.Field( + proto.ENUM, + number=4, + enum=ApiVersion, + ) + + +class ListLogMetricsRequest(proto.Message): + r"""The parameters to ListLogMetrics. + + Attributes: + parent (str): + Required. The name of the project containing the metrics: + + :: + + "projects/[PROJECT_ID]". + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``pageToken`` must be the value of ``nextPageToken`` from + the previous response. The values of other method parameters + should be identical to those in the previous call. + page_size (int): + Optional. The maximum number of results to return from this + request. Non-positive values are ignored. The presence of + ``nextPageToken`` in the response indicates that more + results might be available. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListLogMetricsResponse(proto.Message): + r"""Result returned from ListLogMetrics. + + Attributes: + metrics (MutableSequence[google.cloud.logging_v2.types.LogMetric]): + A list of logs-based metrics. + next_page_token (str): + If there might be more results than appear in this response, + then ``nextPageToken`` is included. To get the next set of + results, call this method again using the value of + ``nextPageToken`` as ``pageToken``. + """ + + @property + def raw_page(self): + return self + + metrics: MutableSequence["LogMetric"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LogMetric", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetLogMetricRequest(proto.Message): + r"""The parameters to GetLogMetric. + + Attributes: + metric_name (str): + Required. The resource name of the desired metric: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]". + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateLogMetricRequest(proto.Message): + r"""The parameters to CreateLogMetric. + + Attributes: + parent (str): + Required. The resource name of the project in which to + create the metric: + + :: + + "projects/[PROJECT_ID]" + + The new metric must be provided in the request. + metric (google.cloud.logging_v2.types.LogMetric): + Required. The new logs-based metric, which + must not have an identifier that already exists. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + metric: "LogMetric" = proto.Field( + proto.MESSAGE, + number=2, + message="LogMetric", + ) + + +class UpdateLogMetricRequest(proto.Message): + r"""The parameters to UpdateLogMetric. + + Attributes: + metric_name (str): + Required. The resource name of the metric to update: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + + The updated metric must be provided in the request and it's + ``name`` field must be the same as ``[METRIC_ID]`` If the + metric does not exist in ``[PROJECT_ID]``, then a new metric + is created. + metric (google.cloud.logging_v2.types.LogMetric): + Required. The updated metric. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + metric: "LogMetric" = proto.Field( + proto.MESSAGE, + number=2, + message="LogMetric", + ) + + +class DeleteLogMetricRequest(proto.Message): + r"""The parameters to DeleteLogMetric. + + Attributes: + metric_name (str): + Required. The resource name of the metric to delete: + + :: + + "projects/[PROJECT_ID]/metrics/[METRIC_ID]". + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ff7fdd1a882345ed5f22d084f4747ba96a2a25 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/__init__.py @@ -0,0 +1,313 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.monitoring import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.monitoring_v3.services.alert_policy_service.async_client import ( + AlertPolicyServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.alert_policy_service.client import ( + AlertPolicyServiceClient, +) +from google.cloud.monitoring_v3.services.group_service.async_client import ( + GroupServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.group_service.client import GroupServiceClient +from google.cloud.monitoring_v3.services.metric_service.async_client import ( + MetricServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.metric_service.client import ( + MetricServiceClient, +) +from google.cloud.monitoring_v3.services.notification_channel_service.async_client import ( + NotificationChannelServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.notification_channel_service.client import ( + NotificationChannelServiceClient, +) +from google.cloud.monitoring_v3.services.query_service.async_client import ( + QueryServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.query_service.client import QueryServiceClient +from google.cloud.monitoring_v3.services.service_monitoring_service.async_client import ( + ServiceMonitoringServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.service_monitoring_service.client import ( + ServiceMonitoringServiceClient, +) +from google.cloud.monitoring_v3.services.snooze_service.async_client import ( + SnoozeServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.snooze_service.client import ( + SnoozeServiceClient, +) +from google.cloud.monitoring_v3.services.uptime_check_service.async_client import ( + UptimeCheckServiceAsyncClient, +) +from google.cloud.monitoring_v3.services.uptime_check_service.client import ( + UptimeCheckServiceClient, +) +from google.cloud.monitoring_v3.types.alert import AlertPolicy +from google.cloud.monitoring_v3.types.alert_service import ( + CreateAlertPolicyRequest, + DeleteAlertPolicyRequest, + GetAlertPolicyRequest, + ListAlertPoliciesRequest, + ListAlertPoliciesResponse, + UpdateAlertPolicyRequest, +) +from google.cloud.monitoring_v3.types.common import ( + Aggregation, + ComparisonType, + ServiceTier, + TimeInterval, + TypedValue, +) +from google.cloud.monitoring_v3.types.dropped_labels import DroppedLabels +from google.cloud.monitoring_v3.types.group import Group +from google.cloud.monitoring_v3.types.group_service import ( + CreateGroupRequest, + DeleteGroupRequest, + GetGroupRequest, + ListGroupMembersRequest, + ListGroupMembersResponse, + ListGroupsRequest, + ListGroupsResponse, + UpdateGroupRequest, +) +from google.cloud.monitoring_v3.types.metric import ( + LabelValue, + Point, + QueryError, + TextLocator, + TimeSeries, + TimeSeriesData, + TimeSeriesDescriptor, +) +from google.cloud.monitoring_v3.types.metric_service import ( + CreateMetricDescriptorRequest, + CreateTimeSeriesError, + CreateTimeSeriesRequest, + CreateTimeSeriesSummary, + DeleteMetricDescriptorRequest, + GetMetricDescriptorRequest, + GetMonitoredResourceDescriptorRequest, + ListMetricDescriptorsRequest, + ListMetricDescriptorsResponse, + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListTimeSeriesRequest, + ListTimeSeriesResponse, + QueryErrorList, + QueryTimeSeriesRequest, + QueryTimeSeriesResponse, +) +from google.cloud.monitoring_v3.types.mutation_record import MutationRecord +from google.cloud.monitoring_v3.types.notification import ( + NotificationChannel, + NotificationChannelDescriptor, +) +from google.cloud.monitoring_v3.types.notification_service import ( + CreateNotificationChannelRequest, + DeleteNotificationChannelRequest, + GetNotificationChannelDescriptorRequest, + GetNotificationChannelRequest, + GetNotificationChannelVerificationCodeRequest, + GetNotificationChannelVerificationCodeResponse, + ListNotificationChannelDescriptorsRequest, + ListNotificationChannelDescriptorsResponse, + ListNotificationChannelsRequest, + ListNotificationChannelsResponse, + SendNotificationChannelVerificationCodeRequest, + UpdateNotificationChannelRequest, + VerifyNotificationChannelRequest, +) +from google.cloud.monitoring_v3.types.service import ( + BasicSli, + DistributionCut, + Range, + RequestBasedSli, + Service, + ServiceLevelIndicator, + ServiceLevelObjective, + TimeSeriesRatio, + WindowsBasedSli, +) +from google.cloud.monitoring_v3.types.service_service import ( + CreateServiceLevelObjectiveRequest, + CreateServiceRequest, + DeleteServiceLevelObjectiveRequest, + DeleteServiceRequest, + GetServiceLevelObjectiveRequest, + GetServiceRequest, + ListServiceLevelObjectivesRequest, + ListServiceLevelObjectivesResponse, + ListServicesRequest, + ListServicesResponse, + UpdateServiceLevelObjectiveRequest, + UpdateServiceRequest, +) +from google.cloud.monitoring_v3.types.snooze import Snooze +from google.cloud.monitoring_v3.types.snooze_service import ( + CreateSnoozeRequest, + GetSnoozeRequest, + ListSnoozesRequest, + ListSnoozesResponse, + UpdateSnoozeRequest, +) +from google.cloud.monitoring_v3.types.span_context import SpanContext +from google.cloud.monitoring_v3.types.uptime import ( + GroupResourceType, + InternalChecker, + SyntheticMonitorTarget, + UptimeCheckConfig, + UptimeCheckIp, + UptimeCheckRegion, +) +from google.cloud.monitoring_v3.types.uptime_service import ( + CreateUptimeCheckConfigRequest, + DeleteUptimeCheckConfigRequest, + GetUptimeCheckConfigRequest, + ListUptimeCheckConfigsRequest, + ListUptimeCheckConfigsResponse, + ListUptimeCheckIpsRequest, + ListUptimeCheckIpsResponse, + UpdateUptimeCheckConfigRequest, +) + +__all__ = ( + "AlertPolicyServiceClient", + "AlertPolicyServiceAsyncClient", + "GroupServiceClient", + "GroupServiceAsyncClient", + "MetricServiceClient", + "MetricServiceAsyncClient", + "NotificationChannelServiceClient", + "NotificationChannelServiceAsyncClient", + "QueryServiceClient", + "QueryServiceAsyncClient", + "ServiceMonitoringServiceClient", + "ServiceMonitoringServiceAsyncClient", + "SnoozeServiceClient", + "SnoozeServiceAsyncClient", + "UptimeCheckServiceClient", + "UptimeCheckServiceAsyncClient", + "AlertPolicy", + "CreateAlertPolicyRequest", + "DeleteAlertPolicyRequest", + "GetAlertPolicyRequest", + "ListAlertPoliciesRequest", + "ListAlertPoliciesResponse", + "UpdateAlertPolicyRequest", + "Aggregation", + "TimeInterval", + "TypedValue", + "ComparisonType", + "ServiceTier", + "DroppedLabels", + "Group", + "CreateGroupRequest", + "DeleteGroupRequest", + "GetGroupRequest", + "ListGroupMembersRequest", + "ListGroupMembersResponse", + "ListGroupsRequest", + "ListGroupsResponse", + "UpdateGroupRequest", + "LabelValue", + "Point", + "QueryError", + "TextLocator", + "TimeSeries", + "TimeSeriesData", + "TimeSeriesDescriptor", + "CreateMetricDescriptorRequest", + "CreateTimeSeriesError", + "CreateTimeSeriesRequest", + "CreateTimeSeriesSummary", + "DeleteMetricDescriptorRequest", + "GetMetricDescriptorRequest", + "GetMonitoredResourceDescriptorRequest", + "ListMetricDescriptorsRequest", + "ListMetricDescriptorsResponse", + "ListMonitoredResourceDescriptorsRequest", + "ListMonitoredResourceDescriptorsResponse", + "ListTimeSeriesRequest", + "ListTimeSeriesResponse", + "QueryErrorList", + "QueryTimeSeriesRequest", + "QueryTimeSeriesResponse", + "MutationRecord", + "NotificationChannel", + "NotificationChannelDescriptor", + "CreateNotificationChannelRequest", + "DeleteNotificationChannelRequest", + "GetNotificationChannelDescriptorRequest", + "GetNotificationChannelRequest", + "GetNotificationChannelVerificationCodeRequest", + "GetNotificationChannelVerificationCodeResponse", + "ListNotificationChannelDescriptorsRequest", + "ListNotificationChannelDescriptorsResponse", + "ListNotificationChannelsRequest", + "ListNotificationChannelsResponse", + "SendNotificationChannelVerificationCodeRequest", + "UpdateNotificationChannelRequest", + "VerifyNotificationChannelRequest", + "BasicSli", + "DistributionCut", + "Range", + "RequestBasedSli", + "Service", + "ServiceLevelIndicator", + "ServiceLevelObjective", + "TimeSeriesRatio", + "WindowsBasedSli", + "CreateServiceLevelObjectiveRequest", + "CreateServiceRequest", + "DeleteServiceLevelObjectiveRequest", + "DeleteServiceRequest", + "GetServiceLevelObjectiveRequest", + "GetServiceRequest", + "ListServiceLevelObjectivesRequest", + "ListServiceLevelObjectivesResponse", + "ListServicesRequest", + "ListServicesResponse", + "UpdateServiceLevelObjectiveRequest", + "UpdateServiceRequest", + "Snooze", + "CreateSnoozeRequest", + "GetSnoozeRequest", + "ListSnoozesRequest", + "ListSnoozesResponse", + "UpdateSnoozeRequest", + "SpanContext", + "InternalChecker", + "SyntheticMonitorTarget", + "UptimeCheckConfig", + "UptimeCheckIp", + "GroupResourceType", + "UptimeCheckRegion", + "CreateUptimeCheckConfigRequest", + "DeleteUptimeCheckConfigRequest", + "GetUptimeCheckConfigRequest", + "ListUptimeCheckConfigsRequest", + "ListUptimeCheckConfigsResponse", + "ListUptimeCheckIpsRequest", + "ListUptimeCheckIpsResponse", + "UpdateUptimeCheckConfigRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc65f8aff384f7c8d80c5ba473ed099c5c63618 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.30.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..55d895b04eb3dd66e66cf8fa6a965e12353295b0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-monitoring package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7e8df64e391a8d48a53650c1e03eee4908542a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/__init__.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import sys + +import google.api_core as api_core + +from google.cloud.monitoring_v3 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.alert_policy_service import ( + AlertPolicyServiceAsyncClient, + AlertPolicyServiceClient, +) +from .services.group_service import GroupServiceAsyncClient, GroupServiceClient +from .services.metric_service import MetricServiceAsyncClient, MetricServiceClient +from .services.notification_channel_service import ( + NotificationChannelServiceAsyncClient, + NotificationChannelServiceClient, +) +from .services.query_service import QueryServiceAsyncClient, QueryServiceClient +from .services.service_monitoring_service import ( + ServiceMonitoringServiceAsyncClient, + ServiceMonitoringServiceClient, +) +from .services.snooze_service import SnoozeServiceAsyncClient, SnoozeServiceClient +from .services.uptime_check_service import ( + UptimeCheckServiceAsyncClient, + UptimeCheckServiceClient, +) +from .types.alert import AlertPolicy +from .types.alert_service import ( + CreateAlertPolicyRequest, + DeleteAlertPolicyRequest, + GetAlertPolicyRequest, + ListAlertPoliciesRequest, + ListAlertPoliciesResponse, + UpdateAlertPolicyRequest, +) +from .types.common import ( + Aggregation, + ComparisonType, + ServiceTier, + TimeInterval, + TypedValue, +) +from .types.dropped_labels import DroppedLabels +from .types.group import Group +from .types.group_service import ( + CreateGroupRequest, + DeleteGroupRequest, + GetGroupRequest, + ListGroupMembersRequest, + ListGroupMembersResponse, + ListGroupsRequest, + ListGroupsResponse, + UpdateGroupRequest, +) +from .types.metric import ( + LabelValue, + Point, + QueryError, + TextLocator, + TimeSeries, + TimeSeriesData, + TimeSeriesDescriptor, +) +from .types.metric_service import ( + CreateMetricDescriptorRequest, + CreateTimeSeriesError, + CreateTimeSeriesRequest, + CreateTimeSeriesSummary, + DeleteMetricDescriptorRequest, + GetMetricDescriptorRequest, + GetMonitoredResourceDescriptorRequest, + ListMetricDescriptorsRequest, + ListMetricDescriptorsResponse, + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListTimeSeriesRequest, + ListTimeSeriesResponse, + QueryErrorList, + QueryTimeSeriesRequest, + QueryTimeSeriesResponse, +) +from .types.mutation_record import MutationRecord +from .types.notification import NotificationChannel, NotificationChannelDescriptor +from .types.notification_service import ( + CreateNotificationChannelRequest, + DeleteNotificationChannelRequest, + GetNotificationChannelDescriptorRequest, + GetNotificationChannelRequest, + GetNotificationChannelVerificationCodeRequest, + GetNotificationChannelVerificationCodeResponse, + ListNotificationChannelDescriptorsRequest, + ListNotificationChannelDescriptorsResponse, + ListNotificationChannelsRequest, + ListNotificationChannelsResponse, + SendNotificationChannelVerificationCodeRequest, + UpdateNotificationChannelRequest, + VerifyNotificationChannelRequest, +) +from .types.service import ( + BasicSli, + DistributionCut, + Range, + RequestBasedSli, + Service, + ServiceLevelIndicator, + ServiceLevelObjective, + TimeSeriesRatio, + WindowsBasedSli, +) +from .types.service_service import ( + CreateServiceLevelObjectiveRequest, + CreateServiceRequest, + DeleteServiceLevelObjectiveRequest, + DeleteServiceRequest, + GetServiceLevelObjectiveRequest, + GetServiceRequest, + ListServiceLevelObjectivesRequest, + ListServiceLevelObjectivesResponse, + ListServicesRequest, + ListServicesResponse, + UpdateServiceLevelObjectiveRequest, + UpdateServiceRequest, +) +from .types.snooze import Snooze +from .types.snooze_service import ( + CreateSnoozeRequest, + GetSnoozeRequest, + ListSnoozesRequest, + ListSnoozesResponse, + UpdateSnoozeRequest, +) +from .types.span_context import SpanContext +from .types.uptime import ( + GroupResourceType, + InternalChecker, + SyntheticMonitorTarget, + UptimeCheckConfig, + UptimeCheckIp, + UptimeCheckRegion, +) +from .types.uptime_service import ( + CreateUptimeCheckConfigRequest, + DeleteUptimeCheckConfigRequest, + GetUptimeCheckConfigRequest, + ListUptimeCheckConfigsRequest, + ListUptimeCheckConfigsResponse, + ListUptimeCheckIpsRequest, + ListUptimeCheckIpsResponse, + UpdateUptimeCheckConfigRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.monitoring_v3") # type: ignore + api_core.check_dependency_versions("google.cloud.monitoring_v3") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.monitoring_v3" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "AlertPolicyServiceAsyncClient", + "GroupServiceAsyncClient", + "MetricServiceAsyncClient", + "NotificationChannelServiceAsyncClient", + "QueryServiceAsyncClient", + "ServiceMonitoringServiceAsyncClient", + "SnoozeServiceAsyncClient", + "UptimeCheckServiceAsyncClient", + "Aggregation", + "AlertPolicy", + "AlertPolicyServiceClient", + "BasicSli", + "ComparisonType", + "CreateAlertPolicyRequest", + "CreateGroupRequest", + "CreateMetricDescriptorRequest", + "CreateNotificationChannelRequest", + "CreateServiceLevelObjectiveRequest", + "CreateServiceRequest", + "CreateSnoozeRequest", + "CreateTimeSeriesError", + "CreateTimeSeriesRequest", + "CreateTimeSeriesSummary", + "CreateUptimeCheckConfigRequest", + "DeleteAlertPolicyRequest", + "DeleteGroupRequest", + "DeleteMetricDescriptorRequest", + "DeleteNotificationChannelRequest", + "DeleteServiceLevelObjectiveRequest", + "DeleteServiceRequest", + "DeleteUptimeCheckConfigRequest", + "DistributionCut", + "DroppedLabels", + "GetAlertPolicyRequest", + "GetGroupRequest", + "GetMetricDescriptorRequest", + "GetMonitoredResourceDescriptorRequest", + "GetNotificationChannelDescriptorRequest", + "GetNotificationChannelRequest", + "GetNotificationChannelVerificationCodeRequest", + "GetNotificationChannelVerificationCodeResponse", + "GetServiceLevelObjectiveRequest", + "GetServiceRequest", + "GetSnoozeRequest", + "GetUptimeCheckConfigRequest", + "Group", + "GroupResourceType", + "GroupServiceClient", + "InternalChecker", + "LabelValue", + "ListAlertPoliciesRequest", + "ListAlertPoliciesResponse", + "ListGroupMembersRequest", + "ListGroupMembersResponse", + "ListGroupsRequest", + "ListGroupsResponse", + "ListMetricDescriptorsRequest", + "ListMetricDescriptorsResponse", + "ListMonitoredResourceDescriptorsRequest", + "ListMonitoredResourceDescriptorsResponse", + "ListNotificationChannelDescriptorsRequest", + "ListNotificationChannelDescriptorsResponse", + "ListNotificationChannelsRequest", + "ListNotificationChannelsResponse", + "ListServiceLevelObjectivesRequest", + "ListServiceLevelObjectivesResponse", + "ListServicesRequest", + "ListServicesResponse", + "ListSnoozesRequest", + "ListSnoozesResponse", + "ListTimeSeriesRequest", + "ListTimeSeriesResponse", + "ListUptimeCheckConfigsRequest", + "ListUptimeCheckConfigsResponse", + "ListUptimeCheckIpsRequest", + "ListUptimeCheckIpsResponse", + "MetricServiceClient", + "MutationRecord", + "NotificationChannel", + "NotificationChannelDescriptor", + "NotificationChannelServiceClient", + "Point", + "QueryError", + "QueryErrorList", + "QueryServiceClient", + "QueryTimeSeriesRequest", + "QueryTimeSeriesResponse", + "Range", + "RequestBasedSli", + "SendNotificationChannelVerificationCodeRequest", + "Service", + "ServiceLevelIndicator", + "ServiceLevelObjective", + "ServiceMonitoringServiceClient", + "ServiceTier", + "Snooze", + "SnoozeServiceClient", + "SpanContext", + "SyntheticMonitorTarget", + "TextLocator", + "TimeInterval", + "TimeSeries", + "TimeSeriesData", + "TimeSeriesDescriptor", + "TimeSeriesRatio", + "TypedValue", + "UpdateAlertPolicyRequest", + "UpdateGroupRequest", + "UpdateNotificationChannelRequest", + "UpdateServiceLevelObjectiveRequest", + "UpdateServiceRequest", + "UpdateSnoozeRequest", + "UpdateUptimeCheckConfigRequest", + "UptimeCheckConfig", + "UptimeCheckIp", + "UptimeCheckRegion", + "UptimeCheckServiceClient", + "VerifyNotificationChannelRequest", + "WindowsBasedSli", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/_dataframe.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/_dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..15c0f1148f2878f5e76a7160327a016b05742201 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/_dataframe.py @@ -0,0 +1,152 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Time series as :mod:`pandas` dataframes.""" + +import itertools + +try: + import pandas +except ImportError: # pragma: NO COVER + pandas = None # type: ignore[assignment] + +from google.cloud import monitoring_v3 + +TOP_RESOURCE_LABELS = ("project_id", "aws_account", "location", "region", "zone") + + +def _extract_header(time_series): + """Return a copy of time_series with the points removed.""" + return monitoring_v3.TimeSeries( + metric=time_series.metric, + resource=time_series.resource, + metric_kind=time_series.metric_kind, + value_type=time_series.value_type, + ) + + +def _extract_labels(time_series): + """Build the combined resource and metric labels, with resource_type.""" + labels = {"resource_type": time_series.resource.type} + labels.update(time_series.resource.labels) + labels.update(time_series.metric.labels) + return labels + + +def _extract_value(typed_value): + """Extract the value from a TypedValue.""" + # There is no equivalent of WhichOneOf in proto-plus + # This may break if the field names have been altered in the + # proto-plus representation + # https://github.com/googleapis/proto-plus-python/issues/137 + value_type = monitoring_v3.TypedValue.pb(typed_value).WhichOneof("value") + return getattr(typed_value, value_type) + + +def _build_dataframe(time_series_iterable, label=None, labels=None): # pragma: NO COVER + """Build a :mod:`pandas` dataframe out of time series. + + :type time_series_iterable: + iterable over :class:`~google.cloud.monitoring_v3.TimeSeries` + :param time_series_iterable: + An iterable (e.g., a query object) yielding time series. + + :type label: str + :param label: + (Optional) The label name to use for the dataframe header. This can be + the name of a resource label or metric label (e.g., + ``"instance_name"``), or the string ``"resource_type"``. + + :type labels: list of strings, or None + :param labels: + A list or tuple of label names to use for the dataframe header. + If more than one label name is provided, the resulting dataframe + will have a multi-level column header. + + Specifying neither ``label`` or ``labels`` results in a dataframe + with a multi-level column header including the resource type and + all available resource and metric labels. + + Specifying both ``label`` and ``labels`` is an error. + + :rtype: :class:`pandas.DataFrame` + :returns: A dataframe where each column represents one time series. + + :raises: :exc:`RuntimeError` if `pandas` is not installed. + """ + if pandas is None: + raise RuntimeError("This method requires `pandas` to be installed.") + + if label is not None: + if labels: + raise ValueError("Cannot specify both `label` and `labels`.") + labels = (label,) + + columns = [] + headers = [] + for time_series in time_series_iterable: + pandas_series = pandas.Series( + data=[_extract_value(point.value) for point in time_series.points], + index=[ + point.interval.end_time.timestamp_pb().ToNanoseconds() + for point in time_series.points + ], + ) + columns.append(pandas_series) + headers.append(_extract_header(time_series)) + + # Implement a smart default of using all available labels. + if labels is None: + resource_labels = set( + itertools.chain.from_iterable(header.resource.labels for header in headers) + ) + metric_labels = set( + itertools.chain.from_iterable(header.metric.labels for header in headers) + ) + labels = ( + ["resource_type"] + + _sorted_resource_labels(resource_labels) + + sorted(metric_labels) + ) + + # Assemble the columns into a DataFrame. + dataframe = pandas.DataFrame.from_records(columns).T + + # Convert the timestamp strings into a DatetimeIndex. + dataframe.index = pandas.to_datetime(dataframe.index) + + # Build a multi-level stack of column headers. Some labels may + # be undefined for some time series. + levels = [] + for key in labels: + level = [_extract_labels(header).get(key, "") for header in headers] + levels.append(level) + + # Build a column Index or MultiIndex. Do not include level names + # in the column header if the user requested a single-level header + # by specifying "label". + dataframe.columns = pandas.MultiIndex.from_arrays( + levels, names=labels if not label else None + ) + + # Sort the rows just in case (since the API doesn't guarantee the + # ordering), and sort the columns lexicographically. + return dataframe.sort_index(axis=0).sort_index(axis=1) + + +def _sorted_resource_labels(labels): + """Sort label names, putting well-known resource labels first.""" + head = [label for label in TOP_RESOURCE_LABELS if label in labels] + tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) + return head + tail diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bcb56c4a4416e7ef45f7fa3e28f1dbb7725e6241 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/gapic_metadata.json @@ -0,0 +1,631 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.monitoring_v3", + "protoPackage": "google.monitoring.v3", + "schema": "1.0", + "services": { + "AlertPolicyService": { + "clients": { + "grpc": { + "libraryClient": "AlertPolicyServiceClient", + "rpcs": { + "CreateAlertPolicy": { + "methods": [ + "create_alert_policy" + ] + }, + "DeleteAlertPolicy": { + "methods": [ + "delete_alert_policy" + ] + }, + "GetAlertPolicy": { + "methods": [ + "get_alert_policy" + ] + }, + "ListAlertPolicies": { + "methods": [ + "list_alert_policies" + ] + }, + "UpdateAlertPolicy": { + "methods": [ + "update_alert_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AlertPolicyServiceAsyncClient", + "rpcs": { + "CreateAlertPolicy": { + "methods": [ + "create_alert_policy" + ] + }, + "DeleteAlertPolicy": { + "methods": [ + "delete_alert_policy" + ] + }, + "GetAlertPolicy": { + "methods": [ + "get_alert_policy" + ] + }, + "ListAlertPolicies": { + "methods": [ + "list_alert_policies" + ] + }, + "UpdateAlertPolicy": { + "methods": [ + "update_alert_policy" + ] + } + } + } + } + }, + "GroupService": { + "clients": { + "grpc": { + "libraryClient": "GroupServiceClient", + "rpcs": { + "CreateGroup": { + "methods": [ + "create_group" + ] + }, + "DeleteGroup": { + "methods": [ + "delete_group" + ] + }, + "GetGroup": { + "methods": [ + "get_group" + ] + }, + "ListGroupMembers": { + "methods": [ + "list_group_members" + ] + }, + "ListGroups": { + "methods": [ + "list_groups" + ] + }, + "UpdateGroup": { + "methods": [ + "update_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GroupServiceAsyncClient", + "rpcs": { + "CreateGroup": { + "methods": [ + "create_group" + ] + }, + "DeleteGroup": { + "methods": [ + "delete_group" + ] + }, + "GetGroup": { + "methods": [ + "get_group" + ] + }, + "ListGroupMembers": { + "methods": [ + "list_group_members" + ] + }, + "ListGroups": { + "methods": [ + "list_groups" + ] + }, + "UpdateGroup": { + "methods": [ + "update_group" + ] + } + } + } + } + }, + "MetricService": { + "clients": { + "grpc": { + "libraryClient": "MetricServiceClient", + "rpcs": { + "CreateMetricDescriptor": { + "methods": [ + "create_metric_descriptor" + ] + }, + "CreateServiceTimeSeries": { + "methods": [ + "create_service_time_series" + ] + }, + "CreateTimeSeries": { + "methods": [ + "create_time_series" + ] + }, + "DeleteMetricDescriptor": { + "methods": [ + "delete_metric_descriptor" + ] + }, + "GetMetricDescriptor": { + "methods": [ + "get_metric_descriptor" + ] + }, + "GetMonitoredResourceDescriptor": { + "methods": [ + "get_monitored_resource_descriptor" + ] + }, + "ListMetricDescriptors": { + "methods": [ + "list_metric_descriptors" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "list_monitored_resource_descriptors" + ] + }, + "ListTimeSeries": { + "methods": [ + "list_time_series" + ] + } + } + }, + "grpc-async": { + "libraryClient": "MetricServiceAsyncClient", + "rpcs": { + "CreateMetricDescriptor": { + "methods": [ + "create_metric_descriptor" + ] + }, + "CreateServiceTimeSeries": { + "methods": [ + "create_service_time_series" + ] + }, + "CreateTimeSeries": { + "methods": [ + "create_time_series" + ] + }, + "DeleteMetricDescriptor": { + "methods": [ + "delete_metric_descriptor" + ] + }, + "GetMetricDescriptor": { + "methods": [ + "get_metric_descriptor" + ] + }, + "GetMonitoredResourceDescriptor": { + "methods": [ + "get_monitored_resource_descriptor" + ] + }, + "ListMetricDescriptors": { + "methods": [ + "list_metric_descriptors" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "list_monitored_resource_descriptors" + ] + }, + "ListTimeSeries": { + "methods": [ + "list_time_series" + ] + } + } + } + } + }, + "NotificationChannelService": { + "clients": { + "grpc": { + "libraryClient": "NotificationChannelServiceClient", + "rpcs": { + "CreateNotificationChannel": { + "methods": [ + "create_notification_channel" + ] + }, + "DeleteNotificationChannel": { + "methods": [ + "delete_notification_channel" + ] + }, + "GetNotificationChannel": { + "methods": [ + "get_notification_channel" + ] + }, + "GetNotificationChannelDescriptor": { + "methods": [ + "get_notification_channel_descriptor" + ] + }, + "GetNotificationChannelVerificationCode": { + "methods": [ + "get_notification_channel_verification_code" + ] + }, + "ListNotificationChannelDescriptors": { + "methods": [ + "list_notification_channel_descriptors" + ] + }, + "ListNotificationChannels": { + "methods": [ + "list_notification_channels" + ] + }, + "SendNotificationChannelVerificationCode": { + "methods": [ + "send_notification_channel_verification_code" + ] + }, + "UpdateNotificationChannel": { + "methods": [ + "update_notification_channel" + ] + }, + "VerifyNotificationChannel": { + "methods": [ + "verify_notification_channel" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NotificationChannelServiceAsyncClient", + "rpcs": { + "CreateNotificationChannel": { + "methods": [ + "create_notification_channel" + ] + }, + "DeleteNotificationChannel": { + "methods": [ + "delete_notification_channel" + ] + }, + "GetNotificationChannel": { + "methods": [ + "get_notification_channel" + ] + }, + "GetNotificationChannelDescriptor": { + "methods": [ + "get_notification_channel_descriptor" + ] + }, + "GetNotificationChannelVerificationCode": { + "methods": [ + "get_notification_channel_verification_code" + ] + }, + "ListNotificationChannelDescriptors": { + "methods": [ + "list_notification_channel_descriptors" + ] + }, + "ListNotificationChannels": { + "methods": [ + "list_notification_channels" + ] + }, + "SendNotificationChannelVerificationCode": { + "methods": [ + "send_notification_channel_verification_code" + ] + }, + "UpdateNotificationChannel": { + "methods": [ + "update_notification_channel" + ] + }, + "VerifyNotificationChannel": { + "methods": [ + "verify_notification_channel" + ] + } + } + } + } + }, + "QueryService": { + "clients": { + "grpc": { + "libraryClient": "QueryServiceClient", + "rpcs": { + "QueryTimeSeries": { + "methods": [ + "query_time_series" + ] + } + } + }, + "grpc-async": { + "libraryClient": "QueryServiceAsyncClient", + "rpcs": { + "QueryTimeSeries": { + "methods": [ + "query_time_series" + ] + } + } + } + } + }, + "ServiceMonitoringService": { + "clients": { + "grpc": { + "libraryClient": "ServiceMonitoringServiceClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "CreateServiceLevelObjective": { + "methods": [ + "create_service_level_objective" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "DeleteServiceLevelObjective": { + "methods": [ + "delete_service_level_objective" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "GetServiceLevelObjective": { + "methods": [ + "get_service_level_objective" + ] + }, + "ListServiceLevelObjectives": { + "methods": [ + "list_service_level_objectives" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + }, + "UpdateServiceLevelObjective": { + "methods": [ + "update_service_level_objective" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServiceMonitoringServiceAsyncClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "CreateServiceLevelObjective": { + "methods": [ + "create_service_level_objective" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "DeleteServiceLevelObjective": { + "methods": [ + "delete_service_level_objective" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "GetServiceLevelObjective": { + "methods": [ + "get_service_level_objective" + ] + }, + "ListServiceLevelObjectives": { + "methods": [ + "list_service_level_objectives" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + }, + "UpdateServiceLevelObjective": { + "methods": [ + "update_service_level_objective" + ] + } + } + } + } + }, + "SnoozeService": { + "clients": { + "grpc": { + "libraryClient": "SnoozeServiceClient", + "rpcs": { + "CreateSnooze": { + "methods": [ + "create_snooze" + ] + }, + "GetSnooze": { + "methods": [ + "get_snooze" + ] + }, + "ListSnoozes": { + "methods": [ + "list_snoozes" + ] + }, + "UpdateSnooze": { + "methods": [ + "update_snooze" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SnoozeServiceAsyncClient", + "rpcs": { + "CreateSnooze": { + "methods": [ + "create_snooze" + ] + }, + "GetSnooze": { + "methods": [ + "get_snooze" + ] + }, + "ListSnoozes": { + "methods": [ + "list_snoozes" + ] + }, + "UpdateSnooze": { + "methods": [ + "update_snooze" + ] + } + } + } + } + }, + "UptimeCheckService": { + "clients": { + "grpc": { + "libraryClient": "UptimeCheckServiceClient", + "rpcs": { + "CreateUptimeCheckConfig": { + "methods": [ + "create_uptime_check_config" + ] + }, + "DeleteUptimeCheckConfig": { + "methods": [ + "delete_uptime_check_config" + ] + }, + "GetUptimeCheckConfig": { + "methods": [ + "get_uptime_check_config" + ] + }, + "ListUptimeCheckConfigs": { + "methods": [ + "list_uptime_check_configs" + ] + }, + "ListUptimeCheckIps": { + "methods": [ + "list_uptime_check_ips" + ] + }, + "UpdateUptimeCheckConfig": { + "methods": [ + "update_uptime_check_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UptimeCheckServiceAsyncClient", + "rpcs": { + "CreateUptimeCheckConfig": { + "methods": [ + "create_uptime_check_config" + ] + }, + "DeleteUptimeCheckConfig": { + "methods": [ + "delete_uptime_check_config" + ] + }, + "GetUptimeCheckConfig": { + "methods": [ + "get_uptime_check_config" + ] + }, + "ListUptimeCheckConfigs": { + "methods": [ + "list_uptime_check_configs" + ] + }, + "ListUptimeCheckIps": { + "methods": [ + "list_uptime_check_ips" + ] + }, + "UpdateUptimeCheckConfig": { + "methods": [ + "update_uptime_check_config" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc65f8aff384f7c8d80c5ba473ed099c5c63618 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "2.30.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..55d895b04eb3dd66e66cf8fa6a965e12353295b0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-monitoring package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/query.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/query.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ff76ffaddcc6cbe8bcaa6f891cae3eda7f1384 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/monitoring_v3/query.py @@ -0,0 +1,641 @@ +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Time series query for the `Google Stackdriver Monitoring API (V3)`_. + +.. _Google Stackdriver Monitoring API (V3): + https://cloud.google.com/monitoring/api/ref_v3/rest/v3/\ + projects.timeSeries/list +""" + +import copy +import datetime + +import google.cloud.monitoring_v3 as monitoring_v3 +from google.cloud.monitoring_v3 import _dataframe, types + +_UTCNOW = datetime.datetime.utcnow # To be replaced by tests. + + +class Query(object): + """Query object for retrieving metric data. + + :type client: :class:`google.cloud.monitoring_v3.gapic. + metric_service_client.MetricServiceClient` + :param client: The client to use. + + :type project: str + :param project: The project ID or number. + + :type metric_type: str + :param metric_type: The metric type name. The default value is + :data:`Query.DEFAULT_METRIC_TYPE + `, + but please note that this default value is provided only for + demonstration purposes and is subject to change. See the + `supported metrics`_. + + :type end_time: :class:`datetime.datetime` + :param end_time: (Optional) The end time (inclusive) of the time interval + for which results should be returned, as a datetime object. + The default is the start of the current minute. + + The start time (exclusive) is determined by combining the + values of ``days``, ``hours``, and ``minutes``, and + subtracting the resulting duration from the end time. + + It is also allowed to omit the end time and duration here, + in which case + :meth:`~google.cloud.monitoring.query.Query.select_interval` + must be called before the query is executed. + + :type days: int + :param days: The number of days in the time interval. + + :type hours: int + :param hours: The number of hours in the time interval. + + :type minutes: int + :param minutes: The number of minutes in the time interval. + + :raises: :exc:`ValueError` if ``end_time`` is specified but + ``days``, ``hours``, and ``minutes`` are all zero. + If you really want to specify a point in time, use + :meth:`~google.cloud.monitoring.query.Query.select_interval`. + + .. _supported metrics: https://cloud.google.com/monitoring/api/metrics + """ + + DEFAULT_METRIC_TYPE = "compute.googleapis.com/instance/cpu/utilization" + + def __init__( + self, + client, + project, + metric_type=DEFAULT_METRIC_TYPE, + end_time=None, + days=0, + hours=0, + minutes=0, + ): + start_time = None + if days or hours or minutes: + if end_time is None: + end_time = _UTCNOW().replace(second=0, microsecond=0) + start_time = end_time - datetime.timedelta( + days=days, hours=hours, minutes=minutes + ) + elif end_time is not None: + raise ValueError("Non-zero duration required for time interval.") + + self._client = client + self._project_path = f"projects/{project}" + self._end_time = end_time + self._start_time = start_time + self._filter = _Filter(metric_type) + + self._per_series_aligner = 0 + self._alignment_period_seconds = 0 + self._cross_series_reducer = 0 + self._group_by_fields = () + + def __iter__(self): + return self.iter() + + @property + def metric_type(self): + """The metric type name.""" + return self._filter.metric_type + + @property + def filter(self): + """The filter string. + + This is constructed from the metric type, the resource type, and + selectors for the group ID, monitored projects, resource labels, + and metric labels. + """ + return str(self._filter) + + def select_interval(self, end_time, start_time=None): + """Copy the query and set the query time interval. + + Example:: + + import datetime + + now = datetime.datetime.utcnow() + query = query.select_interval( + end_time=now, + start_time=now - datetime.timedelta(minutes=5)) + + As a convenience, you can alternatively specify the end time and + an interval duration when you create the query initially. + + :type end_time: :class:`datetime.datetime` + :param end_time: The end time (inclusive) of the time interval + for which results should be returned, as a datetime object. + + :type start_time: :class:`datetime.datetime` + :param start_time: + (Optional) The start time (exclusive) of the time interval + for which results should be returned, as a datetime object. + If not specified, the interval is a point in time. + + :rtype: :class:`Query` + :returns: The new query object. + """ + new_query = copy.deepcopy(self) + new_query._end_time = end_time + new_query._start_time = start_time + return new_query + + def select_group(self, group_id): + """Copy the query and add filtering by group. + + Example:: + + query = query.select_group('1234567') + + :type group_id: str + :param group_id: The ID of a group to filter by. + + :rtype: :class:`Query` + :returns: The new query object. + """ + new_query = copy.deepcopy(self) + new_query._filter.group_id = group_id + return new_query + + def select_projects(self, *args): + """Copy the query and add filtering by monitored projects. + + This is only useful if the target project represents a Stackdriver + account containing the specified monitored projects. + + Examples:: + + query = query.select_projects('project-1') + query = query.select_projects('project-1', 'project-2') + + :type args: tuple + :param args: Project IDs limiting the resources to be included + in the query. + + :rtype: :class:`Query` + :returns: The new query object. + """ + new_query = copy.deepcopy(self) + new_query._filter.projects = args + return new_query + + def select_resources(self, *args, **kwargs): + """Copy the query and add filtering by resource labels. + + See more documentation at: https://cloud.google.com/monitoring/api/v3/filters#comparisons. + + Examples:: + + query = query.select_resources(zone='us-central1-a') + query = query.select_resources(zone_prefix='europe-') + query = query.select_resources(resource_type='gce_instance') + + A keyword argument ``