o
    1 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    ZENABLE_METRICSZ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]r.   r/   intr0   strr1   r2   r3   (Sequence[Callable[[metrics.Info], None]]r4   3Sequence[Callable[[metrics.Info], Awaitable[None]]]r5   r6   r7   r8   Sequence[Union[float, str]]r9   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   x/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/middleware.py
<listcomp>U       z?PrometheusInstrumentatorMiddleware.__init__.<locals>.<listcomp>c                 S  rG   r   rH   rK   r   r   rN   rO   V   rP   )r5   r6   r7   r,   r8   r9   r:   r;   )methodhandlerr   z$Number of HTTP requests in progress.Zlivesum)nameZdocumentationZ
labelnamesZmultiprocess_mode)r<   r&   r'   r(   r)   r*   r+   r/   r0   r1   r2   r:   r;   r-   r.   r3   r   defaultr4   
inprogressr   )selfr<   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   Zdefault_instrumentationlabelsr   r   rN   __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rL   patternrR   r   rN   	<genexpr>       z>PrometheusInstrumentatorMiddleware.__call__.<locals>.<genexpr>messager   rE   rF   c                   sX   | d dkr| d | d t  n| d dkr#| d r# | d 7  | I d H  d S )Nr\   http.response.startheadersstatuszhttp.response.bodybodyr   ri   )rm   rk   response_start_timer[   status_coder   rN   send_wrapper   s   zAPrometheusInstrumentatorMiddleware.__call__.<locals>.send_wrapperc                   s6   | d dkr| d  | d t  | I d H  d S )Nr\   rj   rk   rl   r   rn   )rk   ro   r[   rp   r   rN   rq      s   g        r   xx)raw)contentrk   rp   )requestresponserQ   Zmodified_handlerZmodified_statusZmodified_durationZ#modified_duration_without_streamingc                   s   g | ]}| qS r   r   )rL   instrumentation)infor   rN   rO      s    z?PrometheusInstrumentatorMiddleware.__call__.<locals>.<listcomp>)ri   r   rE   rF   )!r<   r   r   _get_handler_is_handler_excludedr(   rU   r2   rW   rQ   incanyr.   	Exception
isinstancer   r@   valuemaxr+   decr)   roundr/   r&   r   r   r   ZInfor3   asynciogatherr4   )rV   rY   rZ   r[   ru   
start_timeis_templatedZis_excludedrU   rq   excrl   durationZduration_without_streamingrv   rw   r   )rm   rR   rk   rx   ro   r[   rp   rN   __call__}   s   



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


z+PrometheusInstrumentatorMiddleware.__call__ru   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   Zget_route_nameurlrM   )rV   ru   Z
route_namer   r   rN   ry      s   
z/PrometheusInstrumentatorMiddleware._get_handlerrR   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  r`   ra   rb   rd   rf   r   rN   rg     rh   zJPrometheusInstrumentatorMiddleware._is_handler_excluded.<locals>.<genexpr>F)r'   r|   r-   )rV   rR   r   r   rf   rN   rz      s
   
z7PrometheusInstrumentatorMiddleware._is_handler_excludedN)0r<   r   r&   r=   r'   r=   r(   r=   r)   r=   r*   r=   r+   r=   r,   r=   r-   r>   r.   r>   r/   r?   r0   r@   r1   r@   r2   r=   r3   rA   r4   rB   r5   r@   r6   r@   r7   r=   r8   rC   r9   rC   r:   r   r;   rD   rE   rF   )rY   r   rZ   r   r[   r   rE   rF   )ru   r   rE   r   )rR   r@   r   r=   rE   r=   )__name__
__module____qualname__r   rX   r   ry   rz   r   r   r   rN   r      s6    
i
ir   )$
__future__r   r   rI   r]   r   Ztimeitr   typingr   r   r   r	   r
   r   Zprometheus_clientr   r   r   Zstarlette.applicationsr   Zstarlette.datastructuresr   Zstarlette.requestsr   Zstarlette.responsesr   Zstarlette.typesr   r   r   r   Z!prometheus_fastapi_instrumentatorr   r   r   r   r   r   rN   <module>   s     