
    `i%                        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          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                  ^    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
d>d.Zd?d5Zd@d9ZdAd<Zd=S )B"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/   r0   r1   Sequence[str]r2   r3   intr4   strr5   r6   r7   (Sequence[Callable[[metrics.Info], None]]r8   3Sequence[Callable[[metrics.Info], Awaitable[None]]]r9   r:   r;   r<   Sequence[Union[float, str]]r=   r>   r   r?   dictreturnNonec          
        || _         || _        || _        || _        || _        || _        || _        || _        || _        || _	        || _
        || _        || _        d |	D             | _        d |
D             | _        |r|| _        n3t!          j        ||||||| j        |          }|r	|g| _        ng | _        || _        d | _        | j        r*| j
        rdnd}t)          | j	        d|d          | _        d S d S )	Nc                6    g | ]}t          j        |          S r   recompile.0paths     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/prometheus_fastapi_instrumentator/middleware.py
<listcomp>z?PrometheusInstrumentatorMiddleware.__init__.<locals>.<listcomp>U   s"    !Q!Q!Qt"*T"2"2!Q!Q!Q    c                6    g | ]}t          j        |          S r   rM   rP   s     rS   rT   z?PrometheusInstrumentatorMiddleware.__init__.<locals>.<listcomp>V   s"    III4bj..IIIrU   )r9   r:   r;   r0   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/   r3   r4   r5   r6   r>   r?   r1   r2   r7   r   defaultr8   
inprogressr   )selfr@   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   default_instrumentationlabelss                             rS   __init__z+PrometheusInstrumentatorMiddleware.__init__   sl   b )B&)B&(@%-J*&<#5Z2&<#(.!2 *!Q!Q?P!Q!Q!QII=III 	+$4D!!&-o!1!12S2S&;%9+	' 	' 	'# ' +)@(A%%(*%&<#+/5 	 )	  
   $)D!"+	  DOOO	 	rU   scoper   receiver   sendr   c                  K   |d         dk    r|                      ||           d {V S t          |          }t                      }|                     |          \  }|                     |          }|s	| j        rdn|sJ| j        rC| j        r!| j                            |j	                  }n| j        }|
                                 dg dd t          fd| j        D                       rdfd}	n	dfd}		 |                      |||	           d {V  n# t          $ r}
|
d }
~
ww xY w	 t          t                    rt!          j                  nt!                    }|st%          t                      |z
  d          }d}rt%          |z
  d          }| j        r|                                 | j        r*t-          || j                  }t-          || j                  }| j        r|d         dz   }t3          t5                              }t7          j        |||j	        |||          | j        D ]} |           t=          j        fd| j         D               d {V  d S d S # t          t                    rt!          j                  nt!                    }|st%          t                      |z
  d          }d}rt%          |z
  d          }| j        r|                                 | j        r*t-          || j                  }t-          || j                  }| j        r|d         dz   }t3          t5                              }t7          j        |||j	        |||          | j        D ]} |           t=          j        fd| j         D               d {V  w w xY w)Ntypehttpnonei  rU   c              3  B   K   | ]}|                               V  d S NsearchrQ   patternrX   s     rS   	<genexpr>z>PrometheusInstrumentatorMiddleware.__call__.<locals>.<genexpr>   s/      II7w~~g&&IIIIIIrU   messager   rI   rJ   c                   K   | d         dk    r| d         | d         t                      n| d         dk    r| d         r| d         z   |            d {V  d S )Nrh   http.response.startheadersstatuszhttp.response.bodybodyr   )rr   rw   ru   response_start_timerf   status_codes    rS   send_wrapperzAPrometheusInstrumentatorMiddleware.__call__.<locals>.send_wrapper   s      6?&;;;%i0G")("3K*7//''V_(<<<<GFO+Dd7mm#########rU   c                   K   | d         dk    r| d         | d         t                       |            d {V  d S )Nrh   rt   ru   rv   r   )rr   ru   rx   rf   ry   s    rS   rz   zAPrometheusInstrumentatorMiddleware.__call__.<locals>.send_wrapper   s[      6?&;;;%i0G")("3K*7//'d7mm#########rU   g        r   xx)raw)contentru   ry   )requestresponserW   modified_handlermodified_statusmodified_duration#modified_duration_without_streamingc                &    g | ]} |          S r   r   )rQ   instrumentationinfos     rS   rT   z?PrometheusInstrumentatorMiddleware.__call__.<locals>.<listcomp>   s3       + (--  rU   )rr   r   rI   rJ   )!r@   r   r   _get_handler_is_handler_excludedr,   r_   r6   rb   rW   incanyr2   	Exception
isinstancer   rD   valuemaxr/   decr-   roundr3   r*   r   r   r   Infor7   asynciogatherr8   )r`   rd   re   rf   r   
start_timeis_templatedis_excludedr_   rz   excrv   durationduration_without_streamingr   r   rw   rX   ru   r   rx   ry   s      `            @@@@@@rS   __call__z+PrometheusInstrumentatorMiddleware.__call__}   s     =F""%$777777777%.."__
 $ 1 1' : ://FF&U4+HUFFg 	  	t 	% -!_33GNGLL

!_
NN" IIIId6HIIIII 	$	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$$ $ $ $ $ $ $ $ $6	((5'<8888888888 	 	 	I	 9 k:66&K%&&&%%   +};SAA-0*& 14+j8#2 2. = %NN$$$5 $Xt/JKKH162D4O2 2. 1 .#AY-F# 'g*>*>*>K   |#%">%,$*&.8R   (,'< * *O#OD))))n   /3/J           M+ +	 k:66&K%&&&%%   +};SAA-0*& 14+j8#2 2. = %NN$$$5 $Xt/JKKH162D4O2 2. 1 .#AY-F# 'g*>*>*>K   |#%">%,$*&.8R   (,'< * *O#OD))))n   /3/J          M+s+   D2 1J 2
E<D>>EJ EO r   r   Tuple[str, bool]c                R    t          j        |          }|p|j        j        |rdn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urlrR   )r`   r   
route_names      rS   r   z/PrometheusInstrumentatorMiddleware._get_handler   s2     +G44
-W[-z/LttuLLrU   rX   r   c                b    |s	| j         rdS t          f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  B   K   | ]}|                               V  d S rl   rm   ro   s     rS   rq   zJPrometheusInstrumentatorMiddleware._is_handler_excluded.<locals>.<genexpr>  s/      MM7w~~g&&MMMMMMrU   F)r+   r   r1   )r`   rX   r   s    ` rS   r   z7PrometheusInstrumentatorMiddleware._is_handler_excluded   sN      	 > 	4MMMMd6LMMMMM 	4urU   N)0r@   r   r*   rA   r+   rA   r,   rA   r-   rA   r.   rA   r/   rA   r0   rA   r1   rB   r2   rB   r3   rC   r4   rD   r5   rD   r6   rA   r7   rE   r8   rF   r9   rD   r:   rD   r;   rA   r<   rG   r=   rG   r>   r   r?   rH   rI   rJ   )rd   r   re   r   rf   r   rI   rJ   )r   r   rI   r   )rX   rD   r   rA   rI   rA   )__name__
__module____qualname__r   rc   r   r   r   r   rU   rS   r   r      s        
 +/*/)-.3',6;27+-')&',9"'EGVX " "27>
. =J&. _g g g g g gRg g g gRM M M M     rU   r   )$
__future__r   r   rN   ri   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   rU   rS   <module>r      s[   " " " " " "  				                   H H H H H H H H H H H H H H H H @ @ @ @ @ @ @ @ @ @ , , , , , , , , , , , , & & & & & & ( ( ( ( ( ( 9 9 9 9 9 9 9 9 9 9 9 9 > > > > > > > >r r r r r r r r r rrU   