
    ?hf                       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m	Z	 ddl
mZmZmZmZmZmZ ddlmZ ddlZddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 	 ddl4Z4ddl5m6Z6 dZ7ee9e:f   Z;eejx                  jz                  ef   Z=ee-e-f   Z>dZ? G d d      Z@ddZAddZBy# e8$ r dZ7Y Gw xY w)z
Connection class definition.
    )annotationsN)ThreadEvent)AnyDictOptionalTupleUnioncast)urlparse)OAuth2Session)HTTPAdapter)ConnectionErrorReadTimeout)	HTTPError)JSONDecodeError)AuthCredentialsAuthClientCredentials
AuthApiKey)ConnectionConfig)_Auth)
EmbeddedDB)AuthenticationFailedExceptionWeaviateStartUpError)NUMBERS)_check_positive_numis_weaviate_domain_decode_json_response_dict)	_Warnings)weaviate_pb2_grpcTFg      ?c                     e Zd ZdZ	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZddZddZd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$dZed%d       Zej&                  d&d       Zedd       Zd'dZed(d       Zedd       Zd)dZy)*
ConnectionzF
    Connection class used to communicate to a weaviate instance.
    Nc                j   d| _         || _        || _        |	| _        d| _        t
        r|
t        | j                        }t        j                  t        j                  t        j                        }	 |j                  d       |j                  |j                  |
f       |j                  d       |j                          t        j                   |j                   d|
       }t#        j$                  |      | _        ddi| _        |]t/        |t0              st3        dt5        |       d	      |j7                         D ]"  \  }}|| j,                  |j9                         <   $ t;        ||      | _        d
| j,                  v r1|/t?        j@                          | j,                  jC                  d
       |,t/        |tD              rd|jF                  z   | j,                  d
<   |  d| _$        |$tK        |dtL        d       | jO                  |       | jQ                  |       | jS                  |       | jU                         d   | _+        | jV                  dk  r t?        jX                  | jV                         yy# t&        t(        t        j*                  f$ r |j                          Y w xY w)a  
        Initialize a Connection class instance.

        Parameters
        ----------
        url : str
            URL to a running weaviate instance.
        auth_client_secret : weaviate.auth.AuthCredentials, optional
            Credentials to authenticate with a weaviate instance. The credentials are not saved within the client and
            authentication is done via authentication tokens.
        timeout_config : tuple(float, float) or float, optional
            Set the timeout configuration for all requests to the Weaviate server. It can be a
            float or, a tuple of two floats: (connect timeout, read timeout).
            If only one float is passed then both connect and read timeout will be set to
            that value.
        proxies : dict, str or None, optional
            Proxies to be used for requests. Are used by both 'requests' and 'aiohttp'. Can be
            passed as a dict ('requests' format:
            https://docs.python-requests.org/en/stable/user/advanced/#proxies), str (HTTP/HTTPS
            protocols are going to use this proxy) or None.
        trust_env : bool, optional
            Whether to read proxies from the ENV variables: (HTTP_PROXY or http_proxy, HTTPS_PROXY
            or https_proxy).
            NOTE: 'proxies' has priority over 'trust_env', i.e. if 'proxies' is NOT None,
            'trust_env' is ignored.
        additional_headers : Dict[str, Any] or None
            Additional headers to include in the requests, used to set OpenAI key. OpenAI key looks
            like this: {'X-OpenAI-Api-Key': 'KEY'}.
        startup_period : int or None
            How long the client will wait for weaviate to start before raising a RequestsConnectionError.
            If None the client will not wait at all.

        Raises
        ------
        ValueError
            If no authentication credentials provided but the Weaviate server has an OpenID
            configured.
        z/v1Ng      ?   :zcontent-typezapplication/jsonz?'additional_headers' must be of type dict or None. Given type: .authorizationBearer startup_periodF)include_zeroversionz1.14)-_api_version_pathurltimeout_configembedded_db
_grpc_stubhas_grpcr   socketAF_INETSOCK_STREAM
settimeoutconnecthostnameshutdownclosegrpcinsecure_channelr    WeaviateStubConnectionRefusedErrorTimeoutErrortimeout_headers
isinstancedict	TypeErrortypeitemslower_get_proxies_proxiesr   auth_header_and_auth_secretpopr   api_key_shutdown_background_eventr   intwait_for_weaviate_create_sessions_add_adapter_to_sessionget_meta_server_versionweaviate_server_older_than_1_14)selfr-   auth_client_secretr.   proxies	trust_envadditional_headersr)   connection_configr/   	grcp_port
parsed_urlschannelkeyvalues                   Y/home/chris/cleankitchens-env/lib/python3.12/site-packages/weaviate/connect/connection.py__init__zConnection.__init__;   sb   h "'3A&DH 	-!$((+Jfnnf.@.@AAS!		:..	:;

1	//:3F3F2Gq0TU"3"@"@"I ();<)0$7UVZ[mVnUoopq  1668 3
U-2ciik*3 %Wi8 dmm+0B0N113MMo. )j9KZ.X-69K9S9S-SDMM/*;?'%0@#TYZ"">201$$%67#}}y9&(55d6J6JK )M ' 
 	s   4BJ   .J21J2c                    |*t        |t              rt        j                         | _        yd| j
                  v r|t        j                         | _        y| j                  | j                  z   dz   }t        j                  || j                         | j                  | j                        }|j                  dk(  r	 |j                         }|et        |t              sUt#        |||       }|j%                         | _        t        |t&              r| j)                  |       y| j)                          yd| j                   d}t+        | j                        r|dz  }t-        |      |j                  d	k(  r0|.t        j.                          t        j                         | _        yt        j                         | _        y# t        $ r1 t        j                   |       t        j                         | _        Y yw xY w)
aD  Creates a async httpx session and a sync request session.

        Either through authlib.oauth2 if authentication is enabled or a normal request session otherwise.

        Raises
        ------
        ValueError
            If no authentication credentials provided but the Weaviate server has OpenID configured.
        Nr'   z!/.well-known/openid-configuration)headersr?   rV      z9"No login credentials provided. The weaviate instance at z requires login credentials.

                    Please check our documentation at https://weaviate.io/developers/weaviate/client-libraries/python#authentication
                    for more information about how to use authentication.a  

                    You can instantiate the client with login credentials for WCS using

                    client = weaviate.Client(
                      url=YOUR_WEAVIATE_URL,
                      auth_client_secret=weaviate.AuthClientPassword(
                        username = YOUR_WCS_USER,
                        password = YOUR_WCS_PW,
                      ))
                    i  )rA   r   requestsSession_sessionr@   r-   r,   get_get_request_header_timeout_configrH   status_codejsonr   r   auth_cannot_parse_oidc_configr   get_auth_sessionr    _create_background_token_refreshr   r   auth_with_anon_weaviate)rT   rU   oidc_urlresponseresp_authmsgs          r`   rO   zConnection._create_sessions   s    )j9KZ.X$,,.DMdmm+0B0J$,,.DM88d4447ZZ<<,,.((MM	
 3&}} "-jASU_6`d$6= % 6 6 802GH99%@99;STXT\T\S] ^J M
 &dhh/ 
 
C 4C88!!S(-?-K--/$,,.DM$,,.DMK # 77A ( 0 0 2s   >G 7G=<G=c                    d| j                   v r| j                   d   S t        | j                  t              rd| j                  j                  d    S y)Nr'   r(   access_token )r@   rA   rg   r   tokenrT   s    r`   get_current_bearer_tokenz#Connection.get_current_bearer_token   sK    dmm+==11}5T]]00@ABB    c                    t        |j                  |j                        }| j                  j	                  d|       | j                  j	                  d|       y )N)pool_connectionspool_maxsizezhttp://zhttps://)r   session_pool_connectionssession_pool_maxsizerg   mount)rT   rY   adapters      r`   rP   z"Connection._add_adapter_to_session   sH    .GG*??
 	Iw/J0r|   c                ,    t         j                  t              sJ d j                  j                  vr|y j                  j                  j	                  dd      }t                _        d	 fd}t        |||fdd      }|j                          y)
a  Create a background thread that periodically refreshes access and refresh tokens.

        While the underlying library refreshes tokens, it does not have an internal cronjob that checks every
        X-seconds if a token has expired. If there is no activity for longer than the refresh tokens lifetime, it will
        expire. Therefore, refresh manually shortly before expiration time is up.refresh_tokenN
expires_in<   c                T   t        j                  t        | dz
  d             j                  Ej                  j	                         s)	 dt        t        j                        j                  v rt        j                  t              sJ j                  j                  j                  j                  d         j                  _        j                  j                  j                  d      dz
  } n3|J |j                         }|j                         j                  _        t        j                  t        | d             j                  j                  j	                         s'y y y y # t        t         f$ r!}d} t#        j$                  |       Y d }~vd }~ww xY w)N      r   token_endpointr   )timesleepmaxrL   is_setr   r   rg   ry   rA   r   metadatarh   rn   fetch_tokenRequestsHTTPErrorr   r   token_refresh_failed)refresh_timert   new_sessionexcrT   s       r`   periodic_refresh_tokenzKConnection._create_background_token_refresh.<locals>.periodic_refresh_token  sZ   JJs<",a01//;77>>@8&$}dmm*L*R*RR)$--GGG.2mm.I.I MM223CD/+ (,}}':':'>'>|'Lr'Q  %000&+&<&<&>.9.E.E.G+ 

3|Q/0- //;77>>@ <@ <" *;7 8#$L223778s   CE7 7F'F""F'TTokenRefresh)targetargsdaemonname)r   rM   rt   Optional[_Auth]returnNone)	rA   rg   r   ry   rh   r   rL   r   start)rT   rt   r   r   demons   `    r`   ro   z+Connection._create_background_token_refresh  s     $--777$--"5"55%-----11"

 +0''	16 )e$	
 	r|   c                    t        | d      r&| j                  | j                  j                          t        | d      r| j                  j	                          yy)z%Shutdown connection class gracefully.rL   Nrg   )hasattrrL   setrg   r9   rz   s    r`   r9   zConnection.close4  sL     D67//;++//14$MM! %r|   c                    | j                   S )z
        Returns the correct headers for a request.

        Returns
        -------
        dict
            Request header as a dict.
        )r@   rz   s    r`   ri   zConnection._get_request_header?  s     }}r|   c                   | j                   | j                   j                          | j                  | j                  z   |z   }| j                  j                  ||| j                         | j                  | j                  |      S )a  
        Make a DELETE request to the Weaviate server instance.

        Parameters
        ----------
        path : str
            Sub-path to the Weaviate resources. Must be a valid Weaviate sub-path.
            e.g. '/meta' or '/objects', without version.
        weaviate_object : dict, optional
            Object is used as payload for DELETE request. By default None.
        params : dict, optional
            Additional request parameters, by default None

        Returns
        -------
        requests.Response
            The response, if request was successful.

        Raises
        ------
        requests.ConnectionError
            If the DELETE request could not be made.
        r-   rl   rc   r?   rV   params)	r/   ensure_runningr-   r,   rg   deleteri   rj   rH   rT   pathweaviate_objectr   request_urls        r`   r   zConnection.deleteJ  s|    : '++-hh!7!77$>}}## ,,.((MM $ 
 	
r|   c                   | j                   | j                   j                          | j                  | j                  z   |z   }| j                  j                  ||| j                         | j                  | j                  |      S )a  
        Make a PATCH request to the Weaviate server instance.

        Parameters
        ----------
        path : str
            Sub-path to the Weaviate resources. Must be a valid Weaviate sub-path.
            e.g. '/meta' or '/objects', without version.
        weaviate_object : dict
            Object is used as payload for PATCH request.
        params : dict, optional
            Additional request parameters, by default None
        Returns
        -------
        requests.Response
            The response, if request was successful.

        Raises
        ------
        requests.ConnectionError
            If the PATCH request could not be made.
        r   )	r/   r   r-   r,   rg   patchri   rj   rH   r   s        r`   r   zConnection.patcht  s|    8 '++-hh!7!77$>}}"" ,,.((MM # 
 	
r|   c                   | j                   | j                   j                          | j                  | j                  z   |z   }| j                  j                  ||| j                         | j                  | j                  |      S )a  
        Make a POST request to the Weaviate server instance.

        Parameters
        ----------
        path : str
            Sub-path to the Weaviate resources. Must be a valid Weaviate sub-path.
            e.g. '/meta' or '/objects', without version.
        weaviate_object : dict
            Object is used as payload for POST request.
        params : dict, optional
            Additional request parameters, by default None
        external_url: Is an external (non-weaviate) url called

        Returns
        -------
        requests.Response
            The response, if request was successful.

        Raises
        ------
        requests.ConnectionError
            If the POST request could not be made.
        r   )	r/   r   r-   r,   rg   postri   rj   rH   r   s        r`   r   zConnection.post  s|    < '++-hh!7!77$>}}!! ,,.((MM " 
 	
r|   c                   | j                   | j                   j                          | j                  | j                  z   |z   }| j                  j                  ||| j                         | j                  | j                  |      S )a  
        Make a PUT request to the Weaviate server instance.

        Parameters
        ----------
        path : str
            Sub-path to the Weaviate resources. Must be a valid Weaviate sub-path.
            e.g. '/meta' or '/objects', without version.
        weaviate_object : dict
            Object is used as payload for PUT request.
        params : dict, optional
            Additional request parameters, by default None
        Returns
        -------
        requests.Response
            The response, if request was successful.

        Raises
        ------
        requests.ConnectionError
            If the PUT request could not be made.
        r   )	r/   r   r-   r,   rg   putri   rj   rH   r   s        r`   r   zConnection.put  s|    8 '++-hh!7!77$>}}   ,,.((MM ! 
 	
r|   c                   | j                   | j                   j                          |i }|r|}n| j                  | j                  z   |z   }| j                  j                  || j                         | j                  || j                        S )a]  Make a GET request.

        Parameters
        ----------
        path : str
            Sub-path to the Weaviate resources. Must be a valid Weaviate sub-path.
            e.g. '/meta' or '/objects', without version.
        params : dict, optional
            Additional request parameters, by default None
        external_url: Is an external (non-weaviate) url called

        Returns
        -------
        requests.Response
            The response if request was successful.

        Raises
        ------
        requests.ConnectionError
            If the GET request could not be made.
        )r-   rc   r?   r   rV   )	r/   r   r-   r,   rg   rh   ri   rj   rH   )rT   r   r   external_urlr   s        r`   rh   zConnection.get  s    0 '++->FK((T%;%;;dBK}}  ,,.((MM ! 
 	
r|   c                
   | j                   | j                   j                          | j                  | j                  z   |z   }| j                  j                  || j                         | j                  | j                  |      S )a  
        Make a HEAD request to the server.

        Parameters
        ----------
        path : str
            Sub-path to the resources. Must be a valid sub-path.
            e.g. '/meta' or '/objects', without version.
        params : dict, optional
            Additional request parameters, by default None

        Returns
        -------
        requests.Response
            The response to the request.

        Raises
        ------
        requests.ConnectionError
            If the HEAD request could not be made.
        )r-   rc   r?   rV   r   )	r/   r   r-   r,   rg   headri   rj   rH   )rT   r   r   r   s       r`   r   zConnection.head  sy    4 '++-hh!7!77$>}}!!,,.((MM " 
 	
r|   c                    | j                   S )aQ  
        Getter/setter for `timeout_config`.

        Parameters
        ----------
        timeout_config : tuple(float, float), optional
            For Setter only: Set the timeout configuration for all requests to the Weaviate server.
            It can be a float or, a tuple of two floats:
                    (connect timeout, read timeout).
            If only one float is passed then both connect and read timeout will be set to
            that value.

        Returns
        -------
        Tuple[float, float]
            For Getter only: Requests Timeout configuration.
        rj   rz   s    r`   r.   zConnection.timeout_configA  s    ( ###r|   c                    || _         y)zW
        Setter for `timeout_config`. (docstring should be only in the Getter)
        Nr   )rT   r.   s     r`   r.   zConnection.timeout_configW  s      .r|   c                    | j                   S N)rH   rz   s    r`   rV   zConnection.proxies_  s    }}r|   c                   | j                   | j                  z   dz   }t        |      D ]<  }	 t        j                  || j                         t              j                           y 	 t        j                  || j                         t              j                          y# t        t        t        f$ r t        j                  d       Y w xY w# t        t        t        f$ r"}t        d| d| j                    d      |d}~ww xY w)a  
        Waits until weaviate is ready or the timelimit given in 'startup_period' has passed.

        Parameters
        ----------
        startup_period : int
            Describes how long the client will wait for weaviate to start in seconds.

        Raises
        ------
        WeaviateStartUpError
            If weaviate takes longer than the timelimit to respond.
        z/.well-known/ready)rc   r?   Nr   zWeaviate did not start up in z" seconds. Either the Weaviate URL zQ is wrong or Weaviate did not start up in the interval given in 'startup_period'.)r-   r,   rangere   rh   ri   INIT_CHECK_TIMEOUTraise_for_statusr   RequestsConnectionErrorr   r   r   r   )rT   r)   	ready_url_ierrors        r`   rN   zConnection.wait_for_weaviatec  s     HHt5558LL	' 	Bt'?'?'AK]""$		LL4#;#;#=GY  &'>L 

1 "#:KH 	&//??abfbjbjak  l}  ~	s)   8B!(8C !)CCD$DDc                    | j                   S r   )r0   rz   s    r`   	grpc_stubzConnection.grpc_stub  s    r|   c                    | j                   S )z3
        Version of the weaviate instance.
        )rR   rz   s    r`   server_versionzConnection.server_version  s    
 ###r|   c                J    | j                  d      }t        |d      }|J |S )z,
        Returns the meta endpoint.
        z/meta)r   zMeta endpoint)rh   r   )rT   rr   ress      r`   rQ   zConnection.get_meta  s/     888)(?C
r|   )NN)r-   strrU   Optional[AuthCredentials]r.   TIMEOUT_TYPE_RETURNrV   Union[dict, str, None]rW   boolrX   Optional[Dict[str, Any]]r)   Optional[int]rY   r   r/   zOptional[EmbeddedDB]rZ   r   )rU   r   r   r   )r   r   )rY   r   r   r   r   )rt   r   r   r   )r   r   )r   rB   )r   r   r   zOptional[JSONPayload]r   r   r   requests.Response)r   r   r   JSONPayloadr   r   r   r   )NF)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   )r.   r   r   r   )r)   rM   r   r   )r   z(Optional[weaviate_pb2_grpc.WeaviateStub])r   zDict[str, str])__name__
__module____qualname____doc__ra   rO   r{   rP   ro   r9   ri   r   r   r   r   rh   r   propertyr.   setterrV   rN   r   r   rQ    r|   r`   r"   r"   6   s>    -1#'nLnL 6nL ,	nL
 (nL nL 5nL &nL ,nL *nL !nL`E/N10d	"	 26+/	(
(
 /(
 )	(

 
(
\ ,0	'
'
 %'
 )	'

 
'
Z ,0	)
)
 %)
 )	)

 
)
^ ,0	'
'
 %'
 )	'

 
'
T X](
(
!9(
PT(
	(
Z ,0$
$
 )$
 
	$
L $ $* . .  !F   $ $r|   r"   c                     t         j                   j                         } t        t        j                  | j                               | j                  dz  z         S )zp
    Get the current epoch time as an integer.

    Returns
    -------
    int
        Current epoch time.
    g    .A)datetimeutcnowroundr   mktime	timetuplemicrosecond)dtss    r`   _get_epoch_timer     s@     


"
"
$CS]]_-#0EEFFr|   c                    | ?t        | t              r| | dS t        | t              r| S t        dt	        |        d      |si S t
        j                  j                  d      t
        j                  j                  d      f}t
        j                  j                  d      t
        j                  j                  d      f}t        ||z         si S i } t        |      r|d   r|d   n|d	   | d
<   t        |      r|d   r|d   n|d	   | d<   | S )ag  
    Get proxies as dict, compatible with 'requests' library.
    NOTE: 'proxies' has priority over 'trust_env', i.e. if 'proxies' is NOT None, 'trust_env'
    is ignored.

    Parameters
    ----------
    proxies : dict, str or None
        The proxies to use for requests. If it is a dict it should follow 'requests' library
        format (https://docs.python-requests.org/en/stable/user/advanced/#proxies). If it is
        a URL (str), a dict will be constructed with both 'http' and 'https' pointing to that
        URL. If None, no proxies will be used.
    trust_env : bool
        If True, the proxies will be read from ENV VARs (case insensitive):
            HTTP_PROXY/HTTPS_PROXY.
        NOTE: It is ignored if 'proxies' is NOT None.

    Returns
    -------
    dict
        A dictionary with proxies, either set from 'proxies' or read from ENV VARs.
    )httphttpszFIf 'proxies' is not None, it must be of type dict or str. Given type: r&   
HTTP_PROXY
http_proxyHTTPS_PROXYhttps_proxyr   r   r   r   )	rA   r   rB   rC   rD   osenvironrh   any)rV   rW   r   r   s       r`   rG   rG     s   0 gs#   gt$N=/,
 	

 	**...

|0LMJ::>>-0"**..2OPKzK'(	G
:+5a=*Q-jm
;-8^;q>QNr|   )r   rM   )rV   r   rW   r   r   rB   )Cr   
__future__r   r   r   r2   r   	threadingr   r   typingr   r   r   r	   r
   r   urllib.parser   re   $authlib.integrations.requests_clientr   requests.adaptersr   requests.exceptionsr   r   r   r   r   r   weaviate.authr   r   r   weaviate.configr   weaviate.connect.authenticationr   weaviate.embeddedr   weaviate.exceptionsr   r   weaviate.typesr   weaviate.utilr   r   r   weaviate.warningsr   r:   weaviate.proto.v1r    r1   ImportErrorrB   listr   sessionsrf   r   r   r"   r   rG   r   r|   r`   <module>r     s    #  	   # : : !  > ) W > / L L , 1 ( # 
 (3H D$J
!!))=8
9GW,-  b	 b	JG4{  Hs   C   C*)C*