o
    iN#                     @  s|  U 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mZm	Z	 d dl
mZ d dl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 d dlmZ ddlmZmZ e d Z	 ed Z	 e dZ!G dd deZ"dddddddZ#de$d< 	 G dd deZ%G dd dedd Z&eG d!d" d"Z'eG d#d$ d$Z(G d%d& d&eZ)d2d-d.Z*d3d0d1Z+dS )4    )annotationsN)	dataclass)datetimetimezone)Path)	TypedDictcast)urljoin)Console)	IntPrompt)Self)LogfireConfigError   )UnexpectedResponseread_toml_filez.logfirezdefault.tomlzU^(?P<safe_part>pylf_v(?P<version>[0-9]+)_(?P<region>[a-z]+)_)(?P<token>[a-zA-Z0-9]+)$c                   @  s   e Zd ZU ded< ded< dS )_RegionDatastrbase_url
gcp_regionN)__name__
__module____qualname____annotations__ r   r   \/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/logfire/_internal/auth.pyr   !   s   
 r   zhttps://logfire-us.pydantic.devzus-east4)r   r   zhttps://logfire-eu.pydantic.devzeurope-west4)useuzdict[str, _RegionData]REGIONSc                   @  "   e Zd ZU dZded< ded< dS )UserTokenDatazUser token data.r   token
expirationNr   r   r   __doc__r   r   r   r   r   r   3      
 r   c                   @  s   e Zd ZU dZded< dS )UserTokensFileDataz/Content of the file containing the user tokens.zdict[str, UserTokenData]tokensNr"   r   r   r   r   r%   :   s   
 r%   F)totalc                   @  sP   e Zd ZU dZded< ded< ded< edd	d
ZedddZdddZ	dS )	UserTokenzA user token.r   r    r   r!   r   returnr   c                 C  s   | |d ||d dS )Nr    r!   )r    r   r!   r   )clsr   r    r   r   r   from_user_token_dataH   s
   zUserToken.from_user_token_databoolc                 C  s*   t jtjdt | jdjtjdkS )zWhether the token is expired.)tzZ)tzinfo)r   nowr   utcfromisoformatr!   rstripreplace)selfr   r   r   
is_expiredP   s   zUserToken.is_expiredc                 C  s   d}t | j }r|d}|tvrd}|  d| j d}|r3||d|dd d  7 }n	|| jd d 7 }|d7 }|S )	Nr   region (z) - 	safe_partr       z****)PYDANTIC_LOGFIRE_TOKEN_PATTERNmatchr    groupr   upperr   )r5   r7   r<   
token_reprr   r   r   __str__W   s   
"zUserToken.__str__N)r   r   r    r   r)   r   )r)   r,   )r)   r   )
r   r   r   r#   r   classmethodr+   propertyr6   r@   r   r   r   r   r(   @   s   
 r(   c                   @  s^   e Zd ZU dZded< 	 ded< 	 ddd
dZddddZddddZdddZd ddZ	dS )!UserTokenCollectionzA collection of user tokens, read from a user tokens file.

    Args:
        path: The path where the user tokens will be stored. If the path doesn't exist,
            an empty collection is created. Defaults to `~/.logfire/default.toml`.
    zdict[str, UserToken]user_tokensr   pathNPath | Noner)   Nonec                 C  s^   |d ur|nt | _z
ttt| j}W n ty   i }Y nw dd |di  D | _d S )Nc                 S  s$   i | ]\}}|t dd |i|qS )r   r   )r(   ).0urlr    r   r   r   
<dictcomp>~   s   $ z0UserTokenCollection.__init__.<locals>.<dictcomp>r&   )	DEFAULT_FILErE   r   r%   r   FileNotFoundErrorgetitemsrD   )r5   rE   datar   r   r   __init__v   s    zUserTokenCollection.__init__r   
str | Noner(   c                 C  s   t | j }|dur| j|}|du rtd| dnFt|dkr)|d }n;t|dkr`ddd	 t|dd
D }tj	d| ddd t
dt|d D ttjdd}||d  }ntd|jrotd| d|S )a  Get a user token from the collection.

        Args:
            base_url: Only look for user tokens valid for this base URL. If not provided,
                all the tokens of the collection will be considered: if only one token is
                available, it will be used, otherwise the user will be prompted to choose
                a token.

        Raises:
            LogfireConfigError: If no user token is found (no token matched the base URL,
                the collection is empty, or the selected token is expired).
        Nz%No user token was found matching the z8 Logfire URL. Please run `logfire auth` to authenticate.r   r      
c                 s  s4    | ]\}}| d | d|j rdnd dV  qdS )z. r8   expiredvalid)Nr6   )rH   ir    r   r   r   	<genexpr>   s
    
z0UserTokenCollection.get_token.<locals>.<genexpr>)startz/Multiple user tokens found. Please select one:
c                 S  s   g | ]}t |qS r   )r   )rH   rX   r   r   r   
<listcomp>   s    z1UserTokenCollection.get_token.<locals>.<listcomp>)file)choicesconsolezKYou are not logged into Logfire. Please run `logfire auth` to authenticate.zUser token z7 is expired. Please run `logfire auth` to authenticate.)listrD   valuesrM   r   lenjoin	enumerater   askranger
   sysstderrr6   )r5   r   tokens_listr    choices_str
int_choicer   r   r   	get_token   s0   





zUserTokenCollection.get_tokenr,   c                   s>    dur fdd| j  D }n| j  }tdd |D S )a  Check whether the user token collection contains at least one valid user token.

        Args:
            base_url: Only check for user tokens valid for this base URL. If not provided,
                all the tokens of the collection will be considered.
        Nc                 3  s    | ]
}|j  kr|V  qd S Nr   rH   trm   r   r   rY      s    z3UserTokenCollection.is_logged_in.<locals>.<genexpr>c                 s  s    | ]}|j  V  qd S rl   rW   rn   r   r   r   rY      s    )rD   r`   any)r5   r   r&   r   rm   r   is_logged_in   s   
z UserTokenCollection.is_logged_inr   r    r   c                 C  s"   t || | j|< }|   |S )z#Add a user token to the collection.)r(   r+   rD   _dump)r5   r   r    
user_tokenr   r   r   	add_token   s   zUserTokenCollection.add_tokenc                 C  s   | j d0}| j D ]!\}}|d| d |d|j d |d|j d qW d   dS 1 s9w   Y  dS )z<Dump the user token collection as TOML to the provided path.wz	[tokens."z"]
z	token = "z"
zexpiration = "N)rE   openrD   rN   writer    r!   )r5   fr   rs   r   r   r   rr      s   "zUserTokenCollection._dumprl   )rE   rF   r)   rG   )r   rQ   r)   r(   )r   rQ   r)   r,   )r   r   r    r   r)   r(   )r)   rG   )
r   r   r   r#   r   rP   rk   rq   rt   rr   r   r   r   r   rC   g   s   
 
*
rC   c                   @  r   )NewDeviceFlowz.Matches model of the same name in the backend.r   device_codefrontend_auth_urlNr"   r   r   r   r   ry      r$   ry   sessionrequests.Sessionbase_api_urlr   r)   tuple[str, str]c              
   C  st   t  d }t|d}z| j|d|id}t| W n tjy- } ztd|d}~ww |	 }|d |d fS )	aV  Request a device code from the Logfire API.

    Args:
        session: The `requests` session to use.
        base_api_url: The base URL of the Logfire instance.

    Returns:
    return data['device_code'], data['frontend_auth_url']
        The device code and the frontend URL to authenticate the device at, as a `NewDeviceFlow` dict.
    r   z/v1/device-auth/new/machine_name)paramsz Failed to request a device code.Nrz   r{   )
platformunamer	   postr   raise_for_statusrequestsRequestExceptionr   json)r|   r~   r   device_auth_endpointreserO   r   r   r   request_device_code   s   

r   rz   c              
   C  s   t |d| }d}	 z| j|dd}t| W n% tjy> } z|d7 }|dkr/td|td	 W Y d
}~nd
}~ww |	 }|rG|S q)a  Poll the Logfire API for the user token.

    This function will keep polling the API until it receives a user token, not that
    each request should take ~10 seconds as the API endpoint will block waiting for the user to
    complete authentication.

    Args:
        session: The `requests` session to use.
        device_code: The device code to poll for.
        base_api_url: The base URL of the Logfire instance.

    Returns:
        The user token.
    z/v1/device-auth/wait/r   T   )timeoutr      zFailed to poll for token.z%Failed to poll for token. Retrying...N)
r	   rM   r   r   r   r   r   warningswarnr   )r|   rz   r~   auth_endpointerrorsr   r   opt_user_tokenr   r   r   poll_for_token   s"   
r   )r|   r}   r~   r   r)   r   )r|   r}   rz   r   r~   r   r)   r   ),
__future__r   r   rerf   r   dataclassesr   r   r   pathlibr   typingr   r   urllib.parser	   r   rich.consoler
   rich.promptr   typing_extensionsr   logfire.exceptionsr   utilsr   r   homeHOME_LOGFIRErK   compiler;   r   r   r   r   r%   r(   rC   ry   r   r   r   r   r   r   <module>   sR    
&_
