o
    *i"                     @   s  U d dl Z d dl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mZmZmZmZ d dlZd dlmZ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 e e!Z"dZ#eddZ$G dd de%Z&G dd de%Z'G dd deZ(G dd deZ)G dd deZ*ee*e)f Z+eee+eddf Z,ee+ e-d< ede.ded fd d!Z/ed"Z0ed#Z1deddfd$e.d%edeee0ee1ddf f gee0ee1ddf f f fd&d'Z2G d(d) d)ej3Z4dS )*    N)	Generator)contextmanager)	timedelta)wraps)	AnnotatedCallableLiteralOptionalTypeVarUnion)	BaseModelFieldTypeAdapterValidationError)	ParamSpec)__version__)Settings   )Identity      )minutesc                       s8   e Zd ZdZdddedee ddf fddZ  ZS )	StreamLogErrorz@Raised when there's an error streaming logs (build or app logs).Nstatus_codemessager   returnc                   s   t  | || _d S )N)super__init__r   )selfr   r   	__class__ X/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/fastapi_cloud_cli/utils/api.pyr   #   s   
zStreamLogError.__init__)	__name__
__module____qualname____doc__strr	   intr   __classcell__r"   r"   r    r#   r       s    ,r   c                   @   s   e Zd ZdS )TooManyRetriesErrorN)r$   r%   r&   r"   r"   r"   r#   r+   (   s    r+   c                   @   s&   e Zd ZU eed< eed< eed< dS )AppLogEntry	timestampr   levelN)r$   r%   r&   r(   __annotations__r"   r"   r"   r#   r,   ,   s   
 r,   c                   @   s*   e Zd ZU ed ed< dZee ed< dS )BuildLogLineGeneric)completefailedtimeout	heartbeattypeNid)r$   r%   r&   r   r/   r6   r	   r(   r"   r"   r"   r#   r0   2   s   
 r0   c                   @   s6   e Zd ZU dZed ed< eed< dZee ed< dS )BuildLogLineMessager   r5   Nr6   )	r$   r%   r&   r5   r   r/   r(   r6   r	   r"   r"   r"   r#   r7   7   s   
 r7   r5   )discriminatorBuildLogAdapterattempt_numberr   )NNNc                 #   s    d fdd}zd V  W d S  t jt jt jfy0 } ztd| |  W Y d }~d S d }~w t jyy } z=|jjdkrKtd|jj| |  n#z|jj	}W n t
y\   d}Y nw td|jj d	| |jjd
|W Y d }~d S d }~ww )Nr   c                     s*   t d  d} td|   t|  d S )N      zRetrying in %ds (attempt %d))minloggerdebugtimesleep)backoff_secondsr:   r"   r#   _backoffE   s   zattempt.<locals>._backoffzNetwork error (will retry): %si  z Server error %d (will retry): %sz(response body unavailable)zHTTP z: r   r   N)httpxTimeoutExceptionNetworkErrorRemoteProtocolErrorr>   r?   HTTPStatusErrorresponser   text	Exceptionr   )r:   rD   errorerror_detailr"   rC   r#   attemptC   sD   	rP   PTtotal_attemptsr3   c              	      s@   dt tttd d f f dt tttd d f f f fdd}|S )Nfuncr   c              
      s8   t  dtjdtjdttd d f f fdd}|S )Nargskwargsr   c               	   ?   s    t  }tD ]8}t  |  kr td ddt|  | i |E d H  	 W d     d S 1 s<w   Y  q	td d)NzLog streaming timed out after z.0fszFailed after z	 attempts)r@   	monotonicrangetotal_secondsTimeoutErrorrP   r+   )rU   rV   startr:   )rT   r3   rS   r"   r#   wrapperz   s   
$z,attempts.<locals>.decorator.<locals>.wrapper)r   rQ   rU   rV   r   rR   )rT   r]   r3   rS   )rT   r#   	decoratorw   s   .zattempts.<locals>.decorator)r   rQ   r   rR   )rS   r3   r_   r"   r^   r#   attemptsr   s   r`   c                       s   e Zd Zd fddZeeededee	ddf fddZ
dedee	 fd	d
Zeeedededededeeddf f
ddZ  ZS )	APIClientr   Nc                    s@   t  }t }t j|jtdd|j dt	 dd d S )N   zBearer zfastapi-cloud-cli/)Authorizationz
User-Agent)base_urlr3   headers)
r   getr   r   r   base_api_urlrF   Timeouttokenr   )r   settingsidentityr    r"   r#   r      s   

zAPIClient.__init__deployment_idc                 c   s    d }	 |r
d|ind }| j dd| dd|dV}|  | D ];}|r*| s+q"| | }r]|jr8|j}|jdkr@|V  |jd	v rQ|V   W d    d S |jd
kr]td  nq"td t	
dW d    n1 srw   Y  td q)NTlast_idGETz/deployments/z/build-logs<   )r3   paramsr   )r1   r2   r3   zReceived timeout; reconnectingz4Connection closed by server unexpectedly; will retryz(Connection closed without terminal stateg      ?)streamraise_for_status
iter_linesstrip_parse_log_liner6   r5   r>   r?   rF   rH   r@   rA   )r   rl   rm   rp   rK   linelog_liner"   r"   r#   stream_build_logs   sD   







zAPIClient.stream_build_logsrv   c              
   C   sP   zt |W S  ttjfy' } ztd|d d | W Y d }~d S d }~ww )Nz&Skipping malformed log: %s (error: %s)d   )r9   validate_jsonr   jsonJSONDecodeErrorr>   r?   )r   rv   er"   r"   r#   ru      s   zAPIClient._parse_log_lineapp_idtailsincefollowc           
      c   s   |rdnd}| j dd| d|||d|dk}|  | D ]Y}|r)| s*q!zt|}W n tjyA   td| Y q!w |	d	d
krJq!|	d	dkrYt
|	ddzt|V  W q! tyz }	 ztd||	 W Y d }	~	q!d }	~	ww W d    d S 1 sw   Y  d S )Nx   r<   rn   z/apps/z/logs/stream)r   r   r   )rp   r3   zFailed to parse log line: %sr5   r4   rN   r   zUnknown errorz"Failed to parse log entry: %s - %s)rq   rr   rs   rt   r{   loadsr|   r>   r?   rf   r   r,   model_validater   )
r   r~   r   r   r   r3   rK   rv   datar}   r"   r"   r#   stream_app_logs   sF   
	"zAPIClient.stream_app_logsrE   )r$   r%   r&   r   r`   STREAM_LOGS_MAX_RETRIESSTREAM_LOGS_TIMEOUTr(   r   BuildLogLinerx   r	   ru   r)   boolr,   r   r*   r"   r"   r    r#   ra      s*    )ra   )5r{   loggingr@   collections.abcr   
contextlibr   datetimer   	functoolsr   typingr   r   r   r	   r
   r   rF   pydanticr   r   r   r   typing_extensionsr   fastapi_cloud_clir   fastapi_cloud_cli.configr   authr   	getLoggerr$   r>   r   r   rM   r   r+   r,   r0   r7   r   r9   r/   r)   rP   rQ   rR   r`   Clientra   r"   r"   r"   r#   <module>   sR   
  	

*
,
