o
    /ia                     @   s  d Z ddlZddlZddlmZmZmZmZ ddlZddl	Z
ddlZ
ddlZ
ddlZ
ddlZ
ddlZddlmZmZ e
jjZedd dkr`zddlZede dZW n ey_   d	ZY nw d	ZejejfZed
Zdd Zdd Z G dd dee ej!Z"e"e Z#dd Z$dd Z%							d(ddZ&										d)dee' fddZ(de)de)fddZ*e+ddZ,e+d d!Z-G d"d# d#e.Z/d$d% Z0G d&d' d'ej1Z2dS )*zHelpers for :mod:`grpc`.    N)GenericIteratorOptionalTypeVar)
exceptionsgeneral_helpers   z3.zSupport for grpcio-gcp is deprecated. This feature will be
            removed from `google-api-core` after January 1, 2024. If you need to
            continue to use this feature, please pin to a specific version of
            `google-api-core`.TFPc                 C   s   t | ds| jj| _dS dS )zFix-up gRPC callable attributes.

    gRPC callable lack the ``__name__`` attribute which causes
    :func:`functools.wraps` to error. This adds the attribute if needed.
    __name__N)hasattr	__class__r
   	callable_ r   P/var/www/passon-env/lib/python3.10/site-packages/google/api_core/grpc_helpers.py_patch_callable_name:   s   
r   c                    "   t   t  fdd}|S )z;Map errors for Unary-Unary and Stream-Unary gRPC callables.c               
      s8   z | i |W S  t jy } zt||d }~ww N)grpcRpcErrorr   from_grpc_error)argskwargsexcr   r   r   error_remapped_callableH   s   z3_wrap_unary_errors.<locals>.error_remapped_callabler   	functoolswrapsr   r   r   r   r   _wrap_unary_errorsD   s   r   c                   @   sv   e Zd ZdddZdee fddZdefddZd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )_StreamingResponseIteratorTc                 C   sJ   || _ z|rt| j | _W d S W d S  ty   Y d S  ty$   Y d S w r   )_wrappednext_stored_first_result	TypeErrorStopIteration)selfwrappedprefetch_first_resultr   r   r   __init__S   s   z#_StreamingResponseIterator.__init__returnc                 C   s   | S )z6This iterator is also an iterable that returns itself.r   r&   r   r   r   __iter__d      z#_StreamingResponseIterator.__iter__c              
   C   sN   zt | dr| j}| `|W S t| jW S  tjy& } zt||d}~ww )zGet the next response from the stream.

        Returns:
            protobuf.Message: A single response from the stream.
        r#   N)r   r#   r"   r!   r   r   r   r   )r&   resultr   r   r   r   __next__h   s   
z#_StreamingResponseIterator.__next__c                 C   s   | j |S r   )r!   add_callbackr&   callbackr   r   r   r0   z   s   z'_StreamingResponseIterator.add_callbackc                 C   
   | j  S r   )r!   cancelr+   r   r   r   r4   }      
z!_StreamingResponseIterator.cancelc                 C   r3   r   )r!   coder+   r   r   r   r6      r5   z_StreamingResponseIterator.codec                 C   r3   r   )r!   detailsr+   r   r   r   r7      r5   z"_StreamingResponseIterator.detailsc                 C   r3   r   )r!   initial_metadatar+   r   r   r   r8      r5   z+_StreamingResponseIterator.initial_metadatac                 C   r3   r   )r!   	is_activer+   r   r   r   r9      r5   z$_StreamingResponseIterator.is_activec                 C   r3   r   )r!   time_remainingr+   r   r   r   r:      r5   z)_StreamingResponseIterator.time_remainingc                 C   r3   r   )r!   trailing_metadatar+   r   r   r   r;      r5   z,_StreamingResponseIterator.trailing_metadataN)T)r
   
__module____qualname__r)   r   r	   r,   r/   r0   r4   r6   r7   r8   r9   r:   r;   r   r   r   r   r    R   s    
r    c                    r   )a  Wrap errors for Unary-Stream and Stream-Stream gRPC callables.

    The callables that return iterators require a bit more logic to re-map
    errors when iterating. This wraps both the initial invocation and the
    iterator of the return value to re-map errors.
    c               
      sP   z | i |}t  dd}t||dW S  tjy' } zt||d }~ww )N_prefetch_first_result_T)r(   )getattrr    r   r   r   r   )r   r   r.   prefetch_firstr   r   r   r   r      s   z4_wrap_stream_errors.<locals>.error_remapped_callabler   r   r   r   r   _wrap_stream_errors   s   rA   c                 C   s   t | tr	t| S t| S )a.  Wrap a gRPC callable and map :class:`grpc.RpcErrors` to friendly error
    classes.

    Errors raised by the gRPC callable are mapped to the appropriate
    :class:`google.api_core.exceptions.GoogleAPICallError` subclasses.
    The original `grpc.RpcError` (which is usually also a `grpc.Call`) is
    available from the ``response`` property on the mapped exception. This
    is useful for extracting metadata from the original error.

    Args:
        callable_ (Callable): A gRPC callable.

    Returns:
        Callable: The wrapped gRPC callable.
    )
isinstance_STREAM_WRAP_CLASSESrA   r   r   r   r   r   wrap_errors   s   
rD   c                 C   s   |durt tjt | r|rtd|r"tjj	|||d\} }n| r/tjj
j| ||d} n
tjj||d\} }|rHt| tjj
jrH| |} tjjj }tjjjj| ||d}	t|	}
|rgt||
S t|
S )a	  Create the composite credentials for secure channels.

    Args:
        credentials (google.auth.credentials.Credentials): The credentials. If
            not specified, then this function will attempt to ascertain the
            credentials from the environment using :func:`google.auth.default`.
        credentials_file (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 `google-api-core`.

            .. warning::
                Important: If you accept a credential configuration (credential JSON/File/Stream)
                from an external source for authentication to Google Cloud Platform, you must
                validate it before providing it to any Google API or client library. Providing an
                unvalidated credential configuration to Google APIs or libraries can compromise
                the security of your systems and data. For more information, refer to
                `Validate credential configurations from external sources`_.

            .. _Validate credential configurations from external sources:

            https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
        default_scopes (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`.
        scopes (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`.
        ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
            credentials. This can be used to specify different certificates.
        quota_project_id (str): An optional project to use for billing and quota.
        default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".

    Returns:
        grpc.ChannelCredentials: The composed channel credentials object.

    Raises:
        google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
    Nz<'credentials' and 'credentials_file' are mutually exclusive.)scopesdefault_scopes)default_host)warningswarnr   _CREDENTIALS_FILE_WARNINGDeprecationWarningr   DuplicateCredentialArgsgoogleauthload_credentials_from_filecredentialswith_scopes_if_requireddefaultrB   CredentialsWithQuotaProjectwith_quota_project	transportrequestsRequestr   AuthMetadataPluginmetadata_call_credentialscomposite_channel_credentials"compute_engine_channel_credentials)rP   credentials_filerF   rE   ssl_credentialsquota_project_idrG   _requestmetadata_plugingoogle_auth_credentialsr   r   r   _create_composite_credentials   sB   0





rc   attempt_direct_pathc
              	   K   s   |r|	rt dt|||||||d}tr7|dur%|tjjkr%tdt |	r-tdt t	j
| |fi |
S |	r=t| } tj
| |fd|i|
S )ap  Create a secure channel with credentials.

    Args:
        target (str): The target service address in the format 'hostname:port'.
        credentials (google.auth.credentials.Credentials): The credentials. If
            not specified, then this function will attempt to ascertain the
            credentials from the environment using :func:`google.auth.default`.
        scopes (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`.
        ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
            credentials. This can be used to specify different certificates.
        credentials_file (str): A file with credentials that can be loaded with
            :func:`google.auth.load_credentials_from_file`. This argument is
            mutually exclusive with credentials.

            .. warning::
                Important: If you accept a credential configuration (credential JSON/File/Stream)
                from an external source for authentication to Google Cloud Platform, you must
                validate it before providing it to any Google API or client library. Providing an
                unvalidated credential configuration to Google APIs or libraries can compromise
                the security of your systems and data. For more information, refer to
                `Validate credential configurations from external sources`_.

            .. _Validate credential configurations from external sources:

            https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
        quota_project_id (str): An optional project to use for billing and quota.
        default_scopes (Sequence[str]): Default scopes passed by a Google client
            library. Use 'scopes' for user-defined scopes.
        default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".
        compression (grpc.Compression): An optional value indicating the
            compression method to be used over the lifetime of the channel.
        attempt_direct_path (Optional[bool]): If set, Direct Path will be attempted
            when the request is made. Direct Path is only available within a Google
            Compute Engine (GCE) environment and provides a proxyless connection
            which increases the available throughput, reduces latency, and increases
            reliability. Note:

            - This argument should only be set in a GCE environment and for Services
              that are known to support Direct Path.
            - If this argument is set outside of GCE, then this request will fail
              unless the back-end service happens to have configured fall-back to DNS.
            - If the request causes a `ServiceUnavailable` response, it is recommended
              that the client repeat the request with `attempt_direct_path` set to
              `False` as the Service may not support Direct Path.
            - Using `ssl_credentials` with `attempt_direct_path` set to `True` will
              result in `ValueError` as this combination  is not yet supported.

        kwargs: Additional key-word args passed to
            :func:`grpc_gcp.secure_channel` or :func:`grpc.secure_channel`.
            Note: `grpc_gcp` is only supported in environments with protobuf < 4.0.0.

    Returns:
        grpc.Channel: The created channel.

    Raises:
        google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
        ValueError: If `ssl_credentials` is set and `attempt_direct_path` is set to `True`.
    z7Using ssl_credentials with Direct Path is not supported)rP   r\   rF   rE   r]   r^   rG   NzKThe `compression` argument is ignored for grpc_gcp.secure_channel creation.zSThe `attempt_direct_path` argument is ignored for grpc_gcp.secure_channel creation.compression)
ValueErrorrc   HAS_GRPC_GCPr   CompressionNoCompressionrH   rI   rK   grpc_gcpsecure_channel_modify_target_for_direct_path)targetrP   rE   r]   r\   r^   rF   rG   re   rd   r   composite_credentialsr   r   r   create_channel2  s@   Mro   rm   r*   c                 C   s<   d}|  |d} d}|| vr| dd }d| | } | S )ag  
    Given a target, return a modified version which is compatible with Direct Path.

    Args:
        target (str): The target service address in the format 'hostname[:port]' or
            'dns://hostname[:port]'.

    Returns:
        target (str): The target service address which is converted into a format compatible with Direct Path.
            If the target contains `dns:///` or does not contain `:///`, the target will be converted in
            a format compatible with Direct Path; otherwise the original target will be returned as the
            original target may already denote Direct Path.
    zdns:/// z:///:r   z
google-c2p)replacesplit)rm   
dns_prefixdirect_path_separatortarget_without_portr   r   r   rl     s   rl   _MethodCall)r`   timeoutmetadatarP   re   _ChannelRequest)methodr`   c                   @   s$   e Zd ZdZdd Z	dddZdS )_CallableStubz,Stub for the grpc.*MultiCallable interfaces.c                 C   s.   || _ || _d | _	 d | _	 g | _	 g | _d S r   )_method_channelresponse	responsesrV   calls)r&   r{   channelr   r   r   r)     s   z_CallableStub.__init__Nc                 C   s   | j jt| j| | jt||||| | j| | j}| jd ur8|d u r/t	| j}n	t
dj| jdt|r@||S t|trG||d urM|S t
d| j)Nz@{method}.response and {method}.responses are mutually exclusive.r{   z%Method stub for "{}" has no response.)r~   rV   appendrz   r}   r   rw   r   r   r"   rf   formatcallablerB   	Exception)r&   r`   rx   ry   rP   re   r   r   r   r   __call__  s*   

z_CallableStub.__call__)NNNN)r
   r<   r=   __doc__r)   r   r   r   r   r   r|     s
    r|   c                 C   s   |  dd S )am  Simplifies a gRPC method name.

    When gRPC invokes the channel to create a callable, it gives a full
    method name like "/google.pubsub.v1.Publisher/CreateTopic". This
    returns just the name of the method, in this case "CreateTopic".

    Args:
        method (str): The name of the method.

    Returns:
        str: The simplified name of the method.
    /   )rsplitpopr   r   r   r   _simplify_method_name  s   r   c                   @   s   e Zd ZdZg fddZdd Zdd Z				dd
dZ				dddZ				dddZ					dddZ
dddZdd Zdd ZdS )ChannelStuba  A testing stub for the grpc.Channel interface.

    This can be used to test any client that eventually uses a gRPC channel
    to communicate. By passing in a channel stub, you can configure which
    responses are returned and track which requests are made.

    For example:

    .. code-block:: python

        channel_stub = grpc_helpers.ChannelStub()
        client = FooClient(channel=channel_stub)

        channel_stub.GetFoo.response = foo_pb2.Foo(name='bar')

        foo = client.get_foo(labels=['baz'])

        assert foo.name == 'bar'
        assert channel_stub.GetFoo.requests[0].labels = ['baz']

    Each method on the stub can be accessed and configured on the channel.
    Here's some examples of various configurations:

    .. code-block:: python

        # Return a basic response:

        channel_stub.GetFoo.response = foo_pb2.Foo(name='bar')
        assert client.get_foo().name == 'bar'

        # Raise an exception:
        channel_stub.GetFoo.response = NotFound('...')

        with pytest.raises(NotFound):
            client.get_foo()

        # Use a sequence of responses:
        channel_stub.GetFoo.responses = iter([
            foo_pb2.Foo(name='bar'),
            foo_pb2.Foo(name='baz'),
        ])

        assert client.get_foo().name == 'bar'
        assert client.get_foo().name == 'baz'

        # Use a callable

        def on_get_foo(request):
            return foo_pb2.Foo(name='bar' + request.id)

        channel_stub.GetFoo.response = on_get_foo

        assert client.get_foo(id='123').name == 'bar123'
    c                 C   s   g | _ 	 i | _d S r   )rV   _method_stubs)r&   r   r   r   r   r)   E  s   
zChannelStub.__init__c                 C   s"   t |}t|| | j|< | j| S r   )r   r|   r   )r&   r{   r   r   r   _stub_for_methodL  s   
zChannelStub._stub_for_methodc                 C   s    z| j | W S  ty   tw r   )r   KeyErrorAttributeError)r&   keyr   r   r   __getattr__Q  s
   zChannelStub.__getattr__NFc                 C   
   |  |S )z(grpc.Channel.unary_unary implementation.r   r&   r{   request_serializerresponse_deserializer_registered_methodr   r   r   unary_unaryW     
zChannelStub.unary_unaryc                 C   r   )z)grpc.Channel.unary_stream implementation.r   r   r   r   r   unary_streama  r   zChannelStub.unary_streamc                 C   r   )z)grpc.Channel.stream_unary implementation.r   r   r   r   r   stream_unaryk  r   zChannelStub.stream_unaryc                 C   r   )z*grpc.Channel.stream_stream implementation.r   r   r   r   r   stream_streamu  r   zChannelStub.stream_streamc                 C      dS )z&grpc.Channel.subscribe implementation.Nr   )r&   r2   try_to_connectr   r   r   	subscribe  r-   zChannelStub.subscribec                 C   r   )z(grpc.Channel.unsubscribe implementation.Nr   r1   r   r   r   unsubscribe  r-   zChannelStub.unsubscribec                 C   r   )z"grpc.Channel.close implementation.Nr   r+   r   r   r   close  r-   zChannelStub.close)NNF)F)r
   r<   r=   r   r)   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s0    7	





r   )NNNNNNN)	NNNNNNNNF)3r   collectionsr   typingr   r   r   r   rH   google.authrM   google.auth.credentialsgoogle.auth.transport.grpcgoogle.auth.transport.requestsgoogle.protobufr   google.api_corer   r   protobuf__version__PROTOBUF_VERSIONrj   rI   rK   rg   ImportErrorUnaryStreamMultiCallableStreamStreamMultiCallablerC   r	   r   r   Callr    
GrpcStreamrA   rD   rc   boolro   strrl   
namedtuplerw   rz   objectr|   r   Channelr   r   r   r   r   <module>   sz   
B
l

p6