{% extends '_base.py.j2' %}

{% block content %}
{% import "%namespace/%name/%version/%sub/services/%service/_shared_macros.j2" as shared_macros %}

from collections import OrderedDict
import os
import re
from typing import Callable, Dict, Mapping, MutableMapping, MutableSequence, Optional, {% if service.any_server_streaming %}Iterable, {% endif %}{% if service.any_client_streaming %}Iterator, {% endif %}Sequence, Tuple, Type, Union, cast
{% if api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|list %}
import uuid
{% endif %}
{% if service.any_deprecated %}
import warnings
{% endif %}

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.transport import mtls                            # type: ignore
from google.auth.transport.grpc import SslCredentials             # type: ignore
from google.auth.exceptions import MutualTLSChannelError          # type: ignore
from google.oauth2 import service_account                         # type: ignore

{{ shared_macros.add_google_api_core_version_header_import(service.version) }}
{% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %}
from {{package_path}} 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

{% filter sort_lines %}
{% for method in service.methods.values() %}
{% for ref_type in method.flat_ref_types %}
{{ ref_type.ident.python_import }}
{% endfor %}
{% endfor %}
{% if opts.add_iam_methods or api.has_iam_mixin %}
from google.iam.v1 import iam_policy_pb2  # type: ignore
from google.iam.v1 import policy_pb2  # type: ignore
{% endif %}
{% if api.has_location_mixin %}
from google.cloud.location import locations_pb2 # type: ignore
{% endif %}
{% if api.has_operations_mixin %}
from google.longrunning import operations_pb2 # type: ignore
{% endif %}
{% endfilter %}
from .transports.base import {{ service.name }}Transport, DEFAULT_CLIENT_INFO
{% if 'grpc' in opts.transport %}
from .transports.grpc import {{ service.name }}GrpcTransport
{% endif %}
{% if 'rest' in opts.transport %}
from .transports.rest import {{ service.name }}RestTransport
{% endif %}


class {{ service.client_name }}Meta(type):
    """Metaclass for the {{ service.name }} 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[{{ service.name }}Transport]]
    {% if "grpc" in opts.transport %}
    _transport_registry['grpc'] = {{ service.name }}GrpcTransport
    {% endif %}
    {% if "rest" in opts.transport %}
    _transport_registry["rest"] = {{ service.name }}RestTransport
    {% endif %}

    def get_transport_class(cls,
            label: Optional[str] = None,
            ) -> Type[{{ service.name }}Transport]:
        """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 {{ service.client_name }}(metaclass={{ service.client_name }}Meta):
    """{{ service.meta.doc|rst(width=72, indent=4) }}{% if service.version|length %}
    This class implements API version {{ service.version }}.{% endif %}"""

    @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<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.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")

    DEFAULT_ENDPOINT = {% if service.host %}"{{ service.host }}"{% else %}None{% endif %}

    DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__(  # type: ignore
        DEFAULT_ENDPOINT
    )

    @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:
            {{ service.client_name }}: 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:
            {{ service.client_name }}: 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) -> {{ service.name }}Transport:
        """Returns the transport used by the client instance.

        Returns:
            {{ service.name }}Transport: The transport used by the client
                instance.
        """
        return self._transport

    def __enter__(self) -> "{{ service.client_name }}":
        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()

    {% for message in service.resource_messages|sort(attribute="resource_type") %}
    @staticmethod
    def {{ message.resource_type|snake_case }}_path({% for arg in message.resource_path_args %}{{ arg }}: str,{% endfor %}) -> str:
        """Returns a fully-qualified {{ message.resource_type|snake_case }} string."""
        return "{{ message.resource_path_formatted }}".format({% for arg in message.resource_path_args %}{{ arg }}={{ arg }}, {% endfor %})


    @staticmethod
    def parse_{{ message.resource_type|snake_case }}_path(path: str) -> Dict[str,str]:
        """Parses a {{ message.resource_type|snake_case }} path into its component segments."""
        m = re.match(r"{{ message.path_regex_str }}", path)
        return m.groupdict() if m else {}

    {% endfor %}{# resources #}
    {% for resource_msg in service.common_resources.values()|sort(attribute="type_name") %}
    @staticmethod
    def common_{{ resource_msg.message_type.resource_type|snake_case }}_path({% for arg in resource_msg.message_type.resource_path_args %}{{ arg }}: str, {%endfor %}) -> str:
        """Returns a fully-qualified {{ resource_msg.message_type.resource_type|snake_case }} string."""
        return "{{ resource_msg.message_type.resource_path }}".format({% for arg in resource_msg.message_type.resource_path_args %}{{ arg }}={{ arg }}, {% endfor %})

    @staticmethod
    def parse_common_{{ resource_msg.message_type.resource_type|snake_case }}_path(path: str) -> Dict[str,str]:
        """Parse a {{ resource_msg.message_type.resource_type|snake_case }} path into its component segments."""
        m = re.match(r"{{ resource_msg.message_type.path_regex_str }}", path)
        return m.groupdict() if m else {}

    {% endfor %} {# common resources #}

    def __init__(self, *,
            credentials: Optional[ga_credentials.Credentials] = None,
            transport: Optional[Union[str, {{ service.name }}Transport]] = None,
            client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
            client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
            ) -> None:
        """Instantiates the {{ (service.client_name|snake_case).replace('_', ' ') }}.

        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, {{ service.name }}Transport]]): The
                transport to use. If set to None, a transport is chosen
                automatically.
                {% if 'rest' in opts.transport and not opts.rest_numeric_enums %}
                NOTE: "rest" transport functionality is currently in a
                beta state (preview). We welcome your feedback via an
                issue in this library's source repository.
                {% endif %}
            client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
                client. It won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "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). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS 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.
            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.
        """
        if isinstance(client_options, dict):
            client_options = client_options_lib.from_dict(client_options)
        if client_options is None:
            client_options = client_options_lib.ClientOptions()
        client_options = cast(client_options_lib.ClientOptions, client_options)

        # Create SSL credentials for mutual TLS if needed.

        # Check if google-auth version supports should_use_client_cert for automatic
        # mTLS enablement
        if hasattr(mtls,"should_use_client_cert"):
            use_client_cert = 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`"
                )
            use_client_cert = use_client_cert_str == "true"

        client_cert_source_func = None
        is_mtls = False
        if use_client_cert:
            if client_options.client_cert_source:
                is_mtls = True
                client_cert_source_func = client_options.client_cert_source
            else:
                is_mtls = mtls.has_default_client_cert_source()
                if is_mtls:
                    client_cert_source_func = mtls.default_client_cert_source()
                else:
                    client_cert_source_func = None

        # Figure out which api endpoint to use.
        if client_options.api_endpoint is not None:
            api_endpoint = client_options.api_endpoint
        else:
            use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
            if use_mtls_env == "never":
                api_endpoint = self.DEFAULT_ENDPOINT
            elif use_mtls_env == "always":
                api_endpoint = self.DEFAULT_MTLS_ENDPOINT
            elif use_mtls_env == "auto":
                api_endpoint = self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
            else:
                raise MutualTLSChannelError(
                    "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
                    "values: never, auto, always"
                )

        # Save or instantiate the transport.
        # Ordinarily, we provide the transport, but allowing a custom transport
        # instance provides an extensibility point for unusual situations.
        if isinstance(transport, {{ service.name }}Transport):
            # transport is a {{ service.name }}Transport instance.
            if credentials or client_options.credentials_file:
                raise ValueError("When providing a transport instance, "
                                 "provide its credentials directly.")
            if client_options.scopes:
                raise ValueError(
                    "When providing a transport instance, provide its scopes "
                    "directly."
                )
            self._transport = transport
        else:
            Transport = type(self).get_transport_class(transport)
            self._transport = Transport(
                credentials=credentials,
                credentials_file=client_options.credentials_file,
                host=api_endpoint,
                scopes=client_options.scopes,
                client_cert_source_for_mtls=client_cert_source_func,
                quota_project_id=client_options.quota_project_id,
                client_info=client_info,
                always_use_jwt_access=True,
              )


    {% for method in service.methods.values() %}
    {% if method.operation_service %}{# Extended Operations LRO #}
    def {{ method.name|snake_case }}_unary(self,
    {% else %}
    def {{ method.client_method_name|snake_case }}(self,
    {% endif %}{# Extended Operations LRO #}
            {% if not method.client_streaming %}
            request: Optional[Union[{{ method.input.ident }}, dict]] = None,
            *,
            {% for field in method.flattened_fields.values() %}
            {{ field.name }}: Optional[{{ field.ident }}] = None,
            {% endfor %}
            {% else %}
            requests: Optional[Iterator[{{ method.input.ident }}]] = None,
            *,
            {% endif %}
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Union[float, object] = gapic_v1.method.DEFAULT,
            metadata: Sequence[Tuple[str, str]] = (),
            {% if not method.server_streaming %}
            ) -> {{ method.client_output.ident }}:
            {% else %}
            ) -> Iterable[{{ method.client_output.ident }}]:
            {% endif %}
        r"""{{ method.meta.doc|rst(width=72, indent=8) }}

        Args:
            {% if not method.client_streaming %}
            request (Union[{{ method.input.ident.sphinx }}, dict, None]):
                The request object.{{ " " }}
                {{- method.input.meta.doc|wrap(width=72, offset=36, indent=16) }}
            {% for key, field in method.flattened_fields.items() %}
            {{ field.name }} ({{ field.ident.sphinx }}):
                {{ field.meta.doc|rst(width=72, indent=16) }}
                This corresponds to the ``{{ key }}`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            {% endfor %}
            {% else %}
            requests (Iterator[{{ method.input.ident.sphinx }}]):
                The request object iterator.{{ " " }}
                {{- method.input.meta.doc|wrap(width=72, offset=36, indent=16) }}
            {% endif %}
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        {% if not method.void %}

        Returns:
            {% if not method.server_streaming %}
            {{ method.client_output.ident.sphinx }}:
            {% else %}
            Iterable[{{ method.client_output.ident.sphinx }}]:
            {% endif %}
                {{ method.client_output.meta.doc|rst(width=72, indent=16, source_format="rst") }}
        {% endif %}
        """
        {% if method.is_deprecated %}
        warnings.warn("{{ service.client_name }}.{{ method.name|snake_case }} is deprecated",
            DeprecationWarning)

        {% endif %}
        {% if not method.client_streaming %}
        # Create or coerce a protobuf request object.
        {% if method.flattened_fields %}
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        flattened_params = [{{ method.flattened_fields.values()|join(", ", attribute="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.')

        {% endif %}
        {% if method.input.ident.package != method.ident.package %}{# request lives in a different package, so there is no proto wrapper #}
        if isinstance(request, dict):
            # The request isn't a proto-plus wrapped type,
            # so it must be constructed via keyword expansion.
            request = {{ method.input.ident }}(**request)
        elif not request:
            # Null request, just make one.
            request = {{ method.input.ident }}()
        {% else %}
        # Minor optimization to avoid making a copy if the user passes
        # in a {{ method.input.ident }}.
        # There's no risk of modifying the input as we've already verified
        # there are no flattened fields.
        if not isinstance(request, {{ method.input.ident }}):
            request = {{ method.input.ident }}(request)
        {% endif %} {# different request package #}

        {#- Vanilla python protobuf wrapper types cannot _set_ repeated fields #}
            {% if method.flattened_fields and method.input.ident.package == method.ident.package %}
            # If we have keyword arguments corresponding to fields on the
            # request, apply these.
            {% endif %}
            {% for key, field in method.flattened_fields.items() if not field.repeated or method.input.ident.package == method.ident.package %}
            if {{ field.name }} is not None:
                {# Repeated values is a special case, because values can be lists. #}
                {# In order to not confuse the marshalling logic, extend these fields instead of assigning #}
                {% if field.ident.ident|string() == "struct_pb2.Value" and field.repeated %}
                request.{{ key }}.extend({{ field.name }})
                {% else %}
                request.{{ key }} = {{ field.name }}
                {% endif %}{# struct_pb2.Value #}
            {% endfor %}
            {# Map-y fields can be _updated_, however #}
            {% for key, field in method.flattened_fields.items() if field.repeated and method.input.ident.package != method.ident.package %}
            {% if field.map %} {# map implies repeated, but repeated does NOT imply map#}
            if {{ field.name }}:
                request.{{ key }}.update({{ field.name }})
            {% else %}
            {# And list-y fields can be _extended_ #}
            if {{ field.name }}:
                request.{{ key }}.extend({{ field.name }})
            {% endif %} {# field.map #}
            {% endfor %} {# method.flattened_fields.items() #}
            {% endif %} {# method.client_streaming #}

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[self._transport.{{ method.transport_safe_name|snake_case}}]
        {% if method.field_headers %}

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((
                {% for field_header in method.field_headers %}
                {% if not method.client_streaming %}
                ("{{ field_header.raw }}", request.{{ field_header.disambiguated }}),
                {% endif %}
                {% endfor %}
            )),
        )
        {% endif %}
{{ shared_macros.add_api_version_header_to_metadata(service.version) }}
{{ shared_macros.auto_populate_uuid4_fields(api, method) }}

        # Send the request.
        {%+ if not method.void %}response = {% endif %}rpc(
            {% if not method.client_streaming %}
            request,
            {% else %}
            requests,
            {% endif %}
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )
        {% if method.lro %}

        # Wrap the response in an operation future.
        response = {{ method.client_output.ident.module_alias or method.client_output.ident.module }}.from_gapic(
            response,
            self._transport.operations_client,
            {{ method.lro.response_type.ident }},
            metadata_type={{ method.lro.metadata_type.ident }},
        )
        {% elif method.paged_result_field %}

        # This method is paged; wrap the response in a pager, which provides
        # an `__iter__` convenience method.
        response = {{ method.client_output.ident }}(
            method=rpc,
            request=request,
            response=response,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )
        {% endif %}
        {% if not method.void %}

        # Done; return the response.
        return response
        {% endif %}
        {{ "\n" }}
    {% endfor %}

    {% include '%namespace/%name/%version/%sub/services/%service/_mixins.py.j2' %}

    {# TODO: Remove after https://github.com/googleapis/gapic-generator-python/pull/1240 is merged. #}
    {% if opts.add_iam_methods %}
    def set_iam_policy(
        self,
        request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> policy_pb2.Policy:
        r"""Sets the IAM access control policy on the specified function.

        Replaces any existing policy.

        Args:
            request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`):
                The request object. Request message for `SetIamPolicy`
                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, str]]): Strings which should be
                sent along with the request as metadata.
        Returns:
            ~.policy_pb2.Policy:
                Defines an Identity and Access Management (IAM) policy.
                It is used to specify access control policies for Cloud
                Platform resources.
                A ``Policy`` is a collection of ``bindings``. A
                ``binding`` binds one or more ``members`` to a single
                ``role``. Members can be user accounts, service
                accounts, Google groups, and domains (such as G Suite).
                A ``role`` is a named list of permissions (defined by
                IAM or configured by users). A ``binding`` can
                optionally specify a ``condition``, which is a logic
                expression that further constrains the role binding
                based on attributes about the request and/or target
                resource.

                **JSON Example**

                ::

                    {
                      "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')",
                          }
                        }
                      ]
                    }

                **YAML Example**

                ::

                    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')

                For a description of IAM and its features, see the `IAM
                developer's
                guide <https://cloud.google.com/iam/docs>`__.
        """
        # 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 = iam_policy_pb2.SetIamPolicyRequest(**request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method.wrap_method(
            self._transport.set_iam_policy,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # 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),)),
        )

        # 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[iam_policy_pb2.GetIamPolicyRequest] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> policy_pb2.Policy:
        r"""Gets the IAM access control policy for a function.

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

        Args:
            request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`):
                The request object. Request message for `GetIamPolicy`
                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, str]]): Strings which should be
                sent along with the request as metadata.
        Returns:
            ~.policy_pb2.Policy:
                Defines an Identity and Access Management (IAM) policy.
                It is used to specify access control policies for Cloud
                Platform resources.
                A ``Policy`` is a collection of ``bindings``. A
                ``binding`` binds one or more ``members`` to a single
                ``role``. Members can be user accounts, service
                accounts, Google groups, and domains (such as G Suite).
                A ``role`` is a named list of permissions (defined by
                IAM or configured by users). A ``binding`` can
                optionally specify a ``condition``, which is a logic
                expression that further constrains the role binding
                based on attributes about the request and/or target
                resource.

                **JSON Example**

                ::

                    {
                      "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')",
                          }
                        }
                      ]
                    }

                **YAML Example**

                ::
                    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')

                For a description of IAM and its features, see the `IAM
                developer's
                guide <https://cloud.google.com/iam/docs>`__.
        """
        # 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 = iam_policy_pb2.GetIamPolicyRequest(**request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method.wrap_method(
            self._transport.get_iam_policy,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # 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),)),
        )

        # 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[iam_policy_pb2.TestIamPermissionsRequest] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> iam_policy_pb2.TestIamPermissionsResponse:
        r"""Tests the specified IAM permissions against the IAM access control
            policy for a function.

        If the function does not exist, this will return an empty set
        of permissions, not a NOT_FOUND error.

        Args:
            request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`):
                The request object. Request message for
                `TestIamPermissions` 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, str]]): Strings which should be
                sent along with the request as metadata.
        Returns:
            ~.iam_policy_pb2.TestIamPermissionsResponse:
                Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method.wrap_method(
            self._transport.test_iam_permissions,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # 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),)),
        )

        # Send the request.
        response = rpc(
            request, retry=retry, timeout=timeout, metadata=metadata,)

        # Done; return the response.
        return response
    {% endif %}


DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__)


__all__ = (
    "{{ service.client_name }}",
)
{% endblock %}
