o
    'i%                     @  s   d dl mZ d dlZd dl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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 d dlmZmZmZmZ d dl m!Z!m"Z" G dd dZ#dS )    )annotationsN)
HTTPStatusdefault_timer)	AwaitableCallableOptionalSequenceTupleUnion)REGISTRYCollectorRegistryGauge)	Starlette)Headers)Request)Response)MessageReceiveScopeSend)metricsroutingc                   @  sd   e Zd Zdddddddddddddddddddd	ei d
dBd.d/ZdCd6d7ZdDd;d<ZdEd?d@ZdAS )F"PrometheusInstrumentatorMiddlewareTF    ENABLE_METRICShttp_requests_inprogress )g{Gz?g?g?g333333?皙?g      ?      ?g      ?   g      ?   g      @   g      @r   g      @   g      @
      <   )r   r    r!   )should_group_status_codesshould_ignore_untemplatedshould_group_untemplatedshould_round_latency_decimalsshould_respect_env_var%should_instrument_requests_inprogress!should_exclude_streaming_durationexcluded_handlersbody_handlersround_latency_decimalsenv_var_nameinprogress_nameinprogress_labelsinstrumentationsasync_instrumentationsmetric_namespacemetric_subsystem!should_only_respect_2xx_for_highrlatency_highr_bucketslatency_lowr_bucketsregistrycustom_labelsappr   r(   boolr)   r*   r+   r,   r-   r.   r/   Sequence[str]r0   r1   intr2   strr3   r4   r5   (Sequence[Callable[[metrics.Info], None]]r6   3Sequence[Callable[[metrics.Info], Awaitable[None]]]r7   r8   r9   r:   Sequence[Union[float, str]]r;   r<   r   r=   dictreturnNonec             
   C  s   || _ || _|| _|| _|| _|| _|| _|| _|| _|| _	|| _
|| _|| _dd |	D | _dd |
D | _|r=|| _ntj||||||| j|d}|rR|g| _ng | _|| _d | _| jrq| j
rcdnd}t| j	d|dd	| _d S d S )
Nc                 S     g | ]}t |qS r   recompile.0pathr   r   i/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/middleware.py
<listcomp>U       z?PrometheusInstrumentatorMiddleware.__init__.<locals>.<listcomp>c                 S  rI   r   rJ   rM   r   r   rP   rQ   V   rR   )r7   r8   r9   r.   r:   r;   r<   r=   )methodhandlerr   z$Number of HTTP requests in progress.livesum)namedocumentation
labelnamesmultiprocess_mode)r>   r(   r)   r*   r+   r,   r-   r1   r2   r3   r4   r<   r=   r/   r0   r5   r   defaultr6   
inprogressr   )selfr>   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   default_instrumentationlabelsr   r   rP   __init__   sX   1

z+PrometheusInstrumentatorMiddleware.__init__scoper   receiver   sendr   c                   s  |d dkr|  ||I d H S t|}t }| |\}| |}|s,| jr,dn|sF| jrF| jr?| j|j	}n| j}|
  dg d d tfdd| jD rfd fdd}	n
dfdd}	zz|  |||	I d H  W n ty }
 z|
d }
~
ww W ttrtjnt}|stt | d}d}rt| d}| jr|  | jrt|| j}t|| j}| jr|d d }t tdd}tj|||j	|||d| jD ]}| qtjfdd| j D  I d H  d S d S ttrtjnt}|stt | d}d}r+t| d}| jr3|  | jrCt|| j}t|| j}| jrM|d d }t tdd}tj|||j	|||d| jD ]}| qgtjfdd| j D  I d H  w w )Ntypehttpnonei      c                 3      | ]}|  V  qd S NsearchrN   patternrT   r   rP   	<genexpr>       z>PrometheusInstrumentatorMiddleware.__call__.<locals>.<genexpr>messager   rG   rH   c                   sX   | d dkr| d | d t  n| d dkr#| d r# | d 7  | I d H  d S )Nrc   http.response.startheadersstatuszhttp.response.bodybodyr   rp   )rt   rr   response_start_timerb   status_coder   rP   send_wrapper   s   zAPrometheusInstrumentatorMiddleware.__call__.<locals>.send_wrapperc                   s6   | d dkr| d  | d t  | I d H  d S )Nrc   rq   rr   rs   r   ru   )rr   rv   rb   rw   r   rP   rx      s   g        r   xx)raw)contentrr   rw   )requestresponserS   modified_handlermodified_statusmodified_duration#modified_duration_without_streamingc                   s   g | ]}| qS r   r   )rN   instrumentation)infor   rP   rQ      s    z?PrometheusInstrumentatorMiddleware.__call__.<locals>.<listcomp>)rp   r   rG   rH   )!r>   r   r   _get_handler_is_handler_excludedr*   r[   r4   r^   rS   incanyr0   	Exception
isinstancer   rB   valuemaxr-   decr+   roundr1   r(   r   r   r   Infor5   asynciogatherr6   )r\   r`   ra   rb   r|   
start_timeis_templatedis_excludedr[   rx   excrs   durationduration_without_streamingr}   r   r   )rt   rT   rr   r   rv   rb   rw   rP   __call__}   s   







z+PrometheusInstrumentatorMiddleware.__call__r|   r   Tuple[str, bool]c                 C  s$   t |}|p
|jj|rdfS dfS )ai  Extracts either template or (if no template) path.

        Args:
            request (Request): Python Requests request object.

        Returns:
            Tuple[str, bool]: Tuple with two elements. First element is either
                template or if no template the path. Second element tells you
                if the path is templated or not.
        TF)r   get_route_nameurlrO   )r\   r|   
route_namer   r   rP   r      s   
z/PrometheusInstrumentatorMiddleware._get_handlerrT   r   c                   s.   |s| j rdS t fdd| jD rdS dS )a  Determines if the handler should be ignored.

        Args:
            handler (str): Handler that handles the request.
            is_templated (bool): Shows if the request is templated.

        Returns:
            bool: `True` if excluded, `False` if not.
        Tc                 3  rg   rh   ri   rk   rm   r   rP   rn     ro   zJPrometheusInstrumentatorMiddleware._is_handler_excluded.<locals>.<genexpr>F)r)   r   r/   )r\   rT   r   r   rm   rP   r      s
   
z7PrometheusInstrumentatorMiddleware._is_handler_excludedN)0r>   r   r(   r?   r)   r?   r*   r?   r+   r?   r,   r?   r-   r?   r.   r?   r/   r@   r0   r@   r1   rA   r2   rB   r3   rB   r4   r?   r5   rC   r6   rD   r7   rB   r8   rB   r9   r?   r:   rE   r;   rE   r<   r   r=   rF   rG   rH   )r`   r   ra   r   rb   r   rG   rH   )r|   r   rG   r   )rT   rB   r   r?   rG   r?   )__name__
__module____qualname__r   r_   r   r   r   r   r   r   rP   r      s6    
i
ir   )$
__future__r   r   rK   rd   r   timeitr   typingr   r   r   r	   r
   r   prometheus_clientr   r   r   starlette.applicationsr   starlette.datastructuresr   starlette.requestsr   starlette.responsesr   starlette.typesr   r   r   r   !prometheus_fastapi_instrumentatorr   r   r   r   r   r   rP   <module>   s     