o
    tBhM                     @   s4  d Z ddlmZ ddlZddlZddlZddlZddlmZ	 ddl
Z
ddlmZ ddlZddlZddlmZ ddlmZ z
ddlZddlZW n eyQ   dZY nw ejjZdZd	Zd
ZdZedejZzej dZ!W n eyx   dZ!Y nw ej"dddZ#dZ$dZ%G dd de	Z&G dd dej'Z(dd Z)dJddZ*dd Z+dd Z,dd  Z-d!d" Z.d#d$ Z/d%d& Z0d'd( Z1d)d* Z2dKd,d-Z3dLd/d0Z4d1d2 Z5d3d4 Z6d5d6 Z7d7d8 Z8d9d: Z9d;d< Z:d=d> Z;d?d@ Z<dMdBdCZ=dMdDdEZ>dJdFdGZ?zddHl@mAZA W n ey   e( ZAY nw ejBdjCeAdIZDdS )Nz^Shared helpers for Google Cloud packages.

This module is not part of the public API surface.
    )absolute_importN)local)http_client)duration_pb2)timestamp_pb2z%Y-%m-%dT%H:%M:%S.%fZz%Y-%m-%dT%H:%M:%Sz%H:%M:%S.%fz%H:%M:%Sah  
    (?P<no_fraction>
        \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}  # YYYY-MM-DDTHH:MM:SS
    )
    (                                        # Optional decimal part
     \.                                      # decimal point
     (?P<nanos>\d{1,9})                      # nanoseconds, maybe truncated
    )?
    Z                                        # Zulu
~gcloudconfigurationsconfig_defaultcoreprojectc                       sD   e Zd ZdZ fddZdd Zdd Zdd	 Zed
d Z	  Z
S )_LocalStackzManage a thread-local LIFO stack of resources.

    Intended for use in :class:`google.cloud.datastore.batch.Batch.__enter__`,
    :class:`google.cloud.storage.batch.Batch.__enter__`, etc.
    c                    s   t t|   g | _d S N)superr   __init___stackself	__class__ l/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/google/cloud/_helpers.pyr   P   s   
z_LocalStack.__init__c                 C   s   t t| jS )z)Iterate the stack in LIFO order.
        )iterreversedr   r   r   r   r   __iter__T   s   z_LocalStack.__iter__c                 C   s   | j | dS )z(Push a resource onto our stack.
        N)r   append)r   resourcer   r   r   pushY   s   z_LocalStack.pushc                 C   s
   | j  S )zPop a resource from our stack.

        :rtype: object
        :returns: the top-most resource, after removing it.
        :raises IndexError: if the stack is empty.
        )r   popr   r   r   r   r   ^   s   
z_LocalStack.popc                 C   s   | j r| j d S dS )z~Get the top-most resource

        :rtype: object
        :returns: the top-most item, or None if the stack is empty.
        N)r   r   r   r   r   topg   s   
z_LocalStack.top)__name__
__module____qualname____doc__r   r   r   r   propertyr    __classcell__r   r   r   r   r   I   s    	r   c                       sZ   e Zd ZdZedZdZeZdd Z	 fddZ
dd	 Zd
d Zdd Zdd Z  ZS )_UTCzeBasic UTC implementation.

    Implementing a small surface area to avoid depending on ``pytz``.
    r   UTCc                 C      | j S )zDaylight savings time offset.)_dstr   dtr   r   r   dst|      z_UTC.dstc                    s&   |j du r|j| dS tt| |S )z6Convert a timestamp from (naive) UTC to this timezone.Ntzinfo)r0   replacer   r'   fromutcr+   r   r   r   r2      s   
z_UTC.fromutcc                 C   r)   )zGet the name of this timezone._tznamer+   r   r   r   tzname   r.   z_UTC.tznamec                 C   r)   )zUTC offset of this timezone.)
_utcoffsetr+   r   r   r   	utcoffset   r.   z_UTC.utcoffsetc                 C   s   d| j f S )Nz<%s>r3   r   r   r   r   __repr__   s   z_UTC.__repr__c                 C   r)   r   r3   r   r   r   r   __str__   s   z_UTC.__str__)r!   r"   r#   r$   datetime	timedeltar*   r4   r6   r-   r2   r5   r7   r8   r9   r&   r   r   r   r   r'   r   s    
r'   c                 C   s&   t |ttfstd| |f t|S )a  Ensures an input is a tuple or list.

    This effectively reduces the iterable types allowed to a very short
    whitelist: list and tuple.

    :type arg_name: str
    :param arg_name: Name of argument to use in error message.

    :type tuple_or_list: sequence of str
    :param tuple_or_list: Sequence to be verified.

    :rtype: list of str
    :returns: The ``tuple_or_list`` passed in cast to a ``list``.
    :raises TypeError: if the ``tuple_or_list`` is not a tuple or list.
    z.Expected %s to be a tuple or list. Received %r)
isinstancetuplelist	TypeError)arg_nametuple_or_listr   r   r   _ensure_tuple_or_list   s   rB   c                 C   s   | du rt j \}} | S )aY  Determine default project ID explicitly or implicitly as fall-back.

    See :func:`google.auth.default` for details on how the default project
    is determined.

    :type project: str
    :param project: Optional. The project name to use as default.

    :rtype: str or ``NoneType``
    :returns: Default project if it can be determined.
    N)googleauthdefault)r   _r   r   r   _determine_default_project   s   rG   c                 C   s   t | }|d S )zConvert a zone-aware datetime to integer milliseconds.

    :type when: :class:`datetime.datetime`
    :param when: the datetime to convert

    :rtype: int
    :returns: milliseconds since epoch for ``when``
      )_microseconds_from_datetime)whenmicrosr   r   r   _millis      	rL   c                 C   s   t tj| d S )zConvert timestamp to datetime, assuming UTC.

    :type value: float
    :param value: The timestamp to convert

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the value.
    )microseconds)_EPOCHr:   r;   valuer   r   r   _datetime_from_microseconds   s   	rR   c                 C   s8   | j s	| jtd} | t} tt|  d | j S )zConvert non-none datetime to microseconds.

    :type value: :class:`datetime.datetime`
    :param value: The timestamp to convert.

    :rtype: int
    :returns: The timestamp, in microseconds.
    r/   g    .A)	r0   r1   r(   
astimezoneintcalendartimegm	timetuplemicrosecondrP   r   r   r   rI      s   	
rI   c                 C   s   | durt | S dS )zConvert non-none datetime to timestamp, assuming UTC.

    :type value: :class:`datetime.datetime`
    :param value: (Optional) the timestamp

    :rtype: int, or ``NoneType``
    :returns: the timestamp, in milliseconds, or None
    N)rL   rP   r   r   r   _millis_from_datetime   s   	rY   c                 C   s   t j | d S )zConvert a ISO8601 date string to native datetime date

    :type value: str
    :param value: The date string to convert

    :rtype: :class:`datetime.date`
    :returns: A datetime date object created from the string

    z%Y-%m-%d)r:   strptimedaterP   r   r   r   _date_from_iso8601_date   s   
r\   c                 C   sD   t | dkr	t}nt | dkrt}ntd| tj| | S )a*  Convert a zoneless ISO8601 time string to naive datetime time

    :type value: str
    :param value: The time string to convert

    :rtype: :class:`datetime.time`
    :returns: A datetime time object created from the string
    :raises ValueError: if the value does not match a known format.
          zUnknown time format: {})len_TIMEONLY_NO_FRACTION_TIMEONLY_W_MICROS
ValueErrorformatr:   rZ   time)rQ   fmtr   r   r   _time_from_iso8601_time_naive  s   
rf   c                 C   s   t j | tjtdS )zConvert a microsecond-precision timestamp to a native datetime.

    :type dt_str: str
    :param dt_str: The string to convert.

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the string.
    r/   )r:   rZ   _RFC3339_MICROSr1   r(   )dt_strr   r   r   _rfc3339_to_datetime  s   	ri   c                 C   s   t | }|du rtd| t jf tj|dt}|d}|du r(d}ndt| }t	|d|  }|d }|j
|td	S )
a  Convert a nanosecond-precision timestamp to a native datetime.

    .. note::

       Python datetimes do not support nanosecond precision;  this function
       therefore truncates such values to microseconds.

    :type dt_str: str
    :param dt_str: The string to convert.

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the string.
    :raises ValueError: If the timestamp does not match the RFC 3339
                        regular expression.
    Nz)Timestamp: %r, does not match pattern: %rno_fractionnanosr   	   
   rH   )rX   r0   )_RFC3339_NANOSmatchrb   patternr:   rZ   group_RFC3339_NO_FRACTIONr_   rT   r1   r(   )rh   
with_nanosbare_secondsfractionrK   scalerk   r   r   r   _rfc3339_nanos_to_datetime!  s"   


rw   Tc                 C   s,   |s| j dur| jdd|   } | tS )at  Convert a timestamp to a string.

    :type value: :class:`datetime.datetime`
    :param value: The datetime object to be converted to a string.

    :type ignore_zone: bool
    :param ignore_zone: If True, then the timezone (if any) of the datetime
                        object is ignored.

    :rtype: str
    :returns: The string representing the datetime stamp.
    Nr/   )r0   r1   r7   strftimerg   )rQ   ignore_zoner   r   r   _datetime_to_rfc3339D  s   
rz   asciic                 C   s8   t | tjr| |n| }t |tjr|S td| f )a  Converts a string value to bytes, if necessary.

    Unfortunately, ``six.b`` is insufficient for this task since in
    Python2 it does not modify ``unicode`` objects.

    :type value: str / bytes or unicode
    :param value: The string/bytes value to be converted.

    :type encoding: str
    :param encoding: The encoding to use to convert unicode to bytes. Defaults
                     to "ascii", which will not allow any characters from
                     ordinals larger than 127. Other useful values are
                     "latin-1", which which will only allows byte ordinals
                     (up to 255) and "utf-8", which will encode any unicode
                     that needs to be.

    :rtype: str / bytes
    :returns: The original value converted to bytes (if unicode) or as passed
              in if it started out as bytes.
    :raises TypeError: if the value could not be converted to bytes.
    z"%r could not be converted to bytes)r<   six	text_typeencodebinary_typer?   )rQ   encodingresultr   r   r   	_to_bytesX  s   r   c                 C   s8   t | tjr| dn| }t |tjr|S td| f )ac  Converts bytes to a unicode value, if necessary.

    :type value: bytes
    :param value: bytes value to attempt string conversion on.

    :rtype: str
    :returns: The original value converted to unicode (if bytes) or as passed
              in if it started out as unicode.

    :raises ValueError: if the value could not be converted to unicode.
    zutf-8z$%r could not be converted to unicode)r<   r|   r   decoder}   rb   )rQ   r   r   r   r   _bytes_to_unicodeu  s   r   c                 C   s*   |  }| |std|jj| j|S )ay  Converts an Any protobuf to the specified message type

    Args:
        pb_type (type): the type of the message that any_pb stores an instance
            of.
        any_pb (google.protobuf.any_pb2.Any): the object to be converted.

    Returns:
        pb_type: An instance of the pb_type message.

    Raises:
        TypeError: if the message could not be converted.
    zCould not convert {} to {})Unpackr?   rc   r   r!   )pb_typeany_pbmsgr   r   r   _from_any_pb  s   

r   c                 C   s   t tj| j| jd d S )a1  Convert a Timestamp protobuf to a datetime object.

    :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp`
    :param timestamp_pb: A Google returned timestamp protobuf.

    :rtype: :class:`datetime.datetime`
    :returns: A UTC datetime object converted from a protobuf timestamp.
         @@secondsrN   )rO   r:   r;   r   rk   )timestamp_pbr   r   r   _pb_timestamp_to_datetime  s   	r   c                 C   s   t | }t|S )a  Convert a Timestamp protobuf to an RFC 3339 string.

    :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp`
    :param timestamp_pb: A Google returned timestamp protobuf.

    :rtype: str
    :returns: An RFC 3339 formatted timestamp string.
    )r   rz   )r   	timestampr   r   r   _pb_timestamp_to_rfc3339  rM   r   c                 C   s,   t | }t|d\}}|d }tj||dS )a
  Convert a datetime object to a Timestamp protobuf.

    :type when: :class:`datetime.datetime`
    :param when: the datetime to convert

    :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp`
    :returns: A timestamp protobuf corresponding to the object.
    i@B rH   )r   rk   )rI   divmodr   	Timestamp)rJ   ms_valuer   rK   rk   r   r   r   _datetime_to_pb_timestamp  s   	r   c                 C   s   t  }||  |S )a  Convert a Python timedelta object to a duration protobuf.

    .. note::

        The Python timedelta has a granularity of microseconds while
        the protobuf duration type has a duration of nanoseconds.

    :type timedelta_val: :class:`datetime.timedelta`
    :param timedelta_val: A timedelta object.

    :rtype: :class:`google.protobuf.duration_pb2.Duration`
    :returns: A duration object equivalent to the time delta.
    )r   DurationFromTimedelta)timedelta_valduration_pbr   r   r   _timedelta_to_duration_pb  s   
r   c                 C   s   t j| j| jd dS )a  Convert a duration protobuf to a Python timedelta object.

    .. note::

        The Python timedelta has a granularity of microseconds while
        the protobuf duration type has a duration of nanoseconds.

    :type duration_pb: :class:`google.protobuf.duration_pb2.Duration`
    :param duration_pb: A protobuf duration object.

    :rtype: :class:`datetime.timedelta`
    :returns: The converted timedelta object.
    r   r   )r:   r;   r   rk   )r   r   r   r   _duration_pb_to_timedelta  s   r   c                 C   sh   t |tr
t|}|| }|std| |jf |dur/|d}||kr/td||f |dS )a  Validate a URI path and get the leaf object's name.

    :type path: str
    :param path: URI path containing the name.

    :type project: str
    :param project: (Optional) The project associated with the request. It is
                    included for validation purposes.  If passed as None,
                    disables validation.

    :type template: str
    :param template: Template regex describing the expected form of the path.
                     The regex must have two named groups, 'project' and
                     'name'.

    :rtype: str
    :returns: Name parsed from ``path``.
    :raises ValueError: if the ``path`` is ill-formed or if the project from
                        the ``path`` does not agree with the ``project``
                        passed in.
    z-path "%s" did not match expected pattern "%s"Nr   zEProject from client (%s) should agree with project from resource(%s).name)r<   strrecompilero   rb   rp   rq   )pathr   templatero   found_projectr   r   r   _name_from_project_path  s    




r   r   c                 C   sF   d|t jf }tjjj }d|f}|f| }tjjjj| |||dS )a  Makes a secure channel for an RPC service.

    Uses / depends on gRPC.

    :type credentials: :class:`google.auth.credentials.Credentials`
    :param credentials: The OAuth2 Credentials to use for creating
                        access tokens.

    :type user_agent: str
    :param user_agent: The user agent to be used with API requests.

    :type host: str
    :param host: The host for the service.

    :type extra_options: tuple
    :param extra_options: (Optional) Extra gRPC options used when creating the
                          channel.

    :rtype: :class:`grpc._channel.Channel`
    :returns: gRPC secure channel with credentials attached.
    %s:%dzgrpc.primary_user_agent)options)	r   
HTTPS_PORTrC   rD   	transportrequestsRequestgrpcsecure_authorized_channel)credentials
user_agenthostextra_optionstargethttp_requestuser_agent_optionr   r   r   r   make_secure_channel  s   

r   c                 C   s   t | |||d}||S )a  Makes a secure stub for an RPC service.

    Uses / depends on gRPC.

    :type credentials: :class:`google.auth.credentials.Credentials`
    :param credentials: The OAuth2 Credentials to use for creating
                        access tokens.

    :type user_agent: str
    :param user_agent: The user agent to be used with API requests.

    :type stub_class: type
    :param stub_class: A gRPC stub type for a given service.

    :type host: str
    :param host: The host for the service.

    :type extra_options: tuple
    :param extra_options: (Optional) Extra gRPC options passed when creating
                          the channel.

    :rtype: object, instance of ``stub_class``
    :returns: The stub object used to make gRPC requests to a given API.
    )r   )r   )r   r   
stub_classr   r   channelr   r   r   make_secure_stub<  s   r   c                 C   s,   |du r|}nd||f }t |}| |S )a  Makes an insecure stub for an RPC service.

    Uses / depends on gRPC.

    :type stub_class: type
    :param stub_class: A gRPC stub type for a given service.

    :type host: str
    :param host: The host for the service. May also include the port
                 if ``port`` is unspecified.

    :type port: int
    :param port: (Optional) The port for the service.

    :rtype: object, instance of ``stub_class``
    :returns: The stub object used to make gRPC requests to a given API.
    Nr   )r   insecure_channel)r   r   portr   r   r   r   r   make_insecure_stub[  s
   
r   )r(   r/   r   )T)r{   )r   )Er$   
__future__r   rU   r:   osr   	threadingr   Localr|   	six.movesr   google.authrC   google.auth.transport.requestsgoogle.protobufr   r   r   google.auth.transport.grpcImportErrorutcnow_NOWrg   rr   ra   r`   r   VERBOSErn   r   
expanduser
_USER_ROOTjoin_GCLOUD_CONFIG_FILE_GCLOUD_CONFIG_SECTION_GCLOUD_CONFIG_KEYr   r0   r'   rB   rG   rL   rR   rI   rY   r\   rf   ri   rw   rz   r   r   r   r   r   r   r   r   r   r   r   r   pytzr(   utcfromtimestampr1   rO   r   r   r   r   <module>   s   
)#

#

+
 

