
    `i5                         d dl Z d dl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mZmZmZmZmZmZ d dlmZ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 d d	l m!Z!  G d
 d          Z"dS )    N)Enum)Any	AwaitableCallableListOptionalSequenceUnioncast)CONTENT_TYPE_LATESTREGISTRYCollectorRegistrygenerate_latestmultiprocess)	Starlette)Request)Response)metrics)"PrometheusInstrumentatorMiddlewarec                      e Zd Zdddddddg g dddddfdeded	ed
ededededee         dee         dededededeedf         ddfdZ		 	 	 	 	 d+de
dedededeeeef                  deeeef                  dd fd Z	 	 	 	 d,de
d"ed#ed$ed%eeeeef                           d&edd fd'Zd(eeej        geded         f         f                  dd fd)Zdefd*ZdS )-PrometheusFastApiInstrumentatorTF   ENABLE_METRICShttp_requests_inprogressN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registryreturnc                 ~   || _         || _        || _        || _        || _        || _        || _        |
| _        || _        || _	        || _
        d |D             | _        d |	D             | _        g | _        g | _        dt          j        v rGdt          j        vr9t          j        d         t          j        d<   t#          j        dt&                     |r|| _        nt*          | _        dt          j        v rDt          j        d         }t          j                            |          st1          d| d          dS dS )	a  Create a Prometheus FastAPI (and Starlette) Instrumentator.

        Args:
            should_group_status_codes (bool): Should status codes be grouped into
                `2xx`, `3xx` and so on? Defaults to `True`.

            should_ignore_untemplated (bool): Should requests without a matching
                template be ignored? Defaults to `False`. This means that by
                default a request like `curl -X GET localhost:80/doesnotexist`
                will be ignored.

            should_group_untemplated (bool): Should requests without a matching
                template be grouped to handler `none`? Defaults to `True`.

            should_round_latency_decimals: Should recorded latencies be
                rounded to a certain number of decimals?

            should_respect_env_var (bool): Should the instrumentator only work - for
                example the methods `instrument()` and `expose()` - if a
                certain environment variable is set to `true`? Usecase: A base
                FastAPI app that is used by multiple distinct apps. The apps
                only have to set the variable to be instrumented. Defaults to
                `False`.

            should_instrument_requests_inprogress (bool): Enables a gauge that shows
                the inprogress requests. See also the related args starting
                with `inprogress`. Defaults to `False`.

            should_exclude_streaming_duration: Should the streaming duration be
                excluded? Only relevant if default metrics are used. Defaults
                to `False`.

            excluded_handlers (List[str]): List of strings that will be compiled
                to regex patterns. All matches will be skipped and not
                instrumented. Defaults to `[]`.

            body_handlers (List[str]): List of strings that will be compiled
                to regex patterns to match handlers for the middleware to
                pass through response bodies to instrumentations. So only
                relevant for instrumentations that access `info.response.body`.
                Note that this has a noticeable negative impact on performance
                with responses larger than a few MBs. Defaults to `[]`.

            round_latency_decimals (int): Number of decimals latencies should be
                rounded to. Ignored unless `should_round_latency_decimals` is
                `True`. Defaults to `4`.

            env_var_name (str): Any valid os environment variable name that will
                be checked for existence before instrumentation. Ignored unless
                `should_respect_env_var` is `True`. Defaults to `"ENABLE_METRICS"`.

            inprogress_name (str): Name of the gauge. Defaults to
                `http_requests_inprogress`. Ignored unless
                `should_instrument_requests_inprogress` is `True`.

            inprogress_labels (bool): Should labels `method` and `handler` be
                part of the inprogress label? Ignored unless
                `should_instrument_requests_inprogress` is `True`. Defaults to `False`.

            registry (CollectorRegistry): A custom Prometheus registry to use. If not
                provided, the default `REGISTRY` will be used. This can be useful if
                you need to run multiple apps at the same time, with their own
                registries, for example during testing.

        Raises:
            ValueError: If `PROMETHEUS_MULTIPROC_DIR` env var is found but
                doesn't point to a valid directory.
        c                 6    g | ]}t          j        |          S  recompile.0paths     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/prometheus_fastapi_instrumentator/instrumentation.py
<listcomp>z<PrometheusFastApiInstrumentator.__init__.<locals>.<listcomp>   s"    !Q!Q!Qt"*T"2"2!Q!Q!Q    c                 6    g | ]}t          j        |          S r,   r-   r0   s     r3   r4   z<PrometheusFastApiInstrumentator.__init__.<locals>.<listcomp>   s"    III4bj..IIIr5   prometheus_multiproc_dirPROMETHEUS_MULTIPROC_DIRzpprometheus_multiproc_dir variable has been deprecated in favor of the upper case naming PROMETHEUS_MULTIPROC_DIRz"Env var PROMETHEUS_MULTIPROC_DIR='z' not a directory.N)r   r   r   r   r   r    r!   r$   r%   r&   r'   r"   r#   instrumentationsasync_instrumentationsosenvironwarningswarnDeprecationWarningr(   r   r2   isdir
ValueError)selfr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   pmds                   r3   __init__z(PrometheusFastApiInstrumentator.__init__   si   l *C&)B&(@%-J*&<#5Z21R.&<#(.!2!Q!Q?P!Q!Q!QII=IIIFHWY# '"*44*"*<<57Z*6BJ12 M C"  
  	%$DMM$DM%33*78C7==%%  PPPP   43 r5    g{Gz?g?g?g333333?皙?g      ?      ?g      ?   g      ?   g      @   g      @r   g      @   g      @
      <   rG   rH   rI   appmetric_namespacemetric_subsystem!should_only_respect_2xx_for_highrlatency_highr_bucketslatency_lowr_bucketsc                 @   | j         r|                                 s| S |                    t          | j        | j        | j        | j        | j         | j        | j	        | j
        | j        | j        | j        | j        | j        | j        | j        |||||| j                   | S )a  Performs the instrumentation by adding middleware.

        The middleware iterates through all `instrumentations` and executes them.

        Args:
            app: Starlette app instance. Note that every FastAPI app is a
                Starlette app.

        Raises:
            e: Only raised if app itself throws an exception.

        Returns:
            self: Instrumentator. Builder Pattern.
        )r   r   r   r   r   r    r!   r$   r%   r&   r'   r9   r:   r"   r#   rR   rS   rT   rU   rV   r(   )r   _should_instrumentateadd_middlewarer   r   r   r   r   r    r!   r$   r%   r&   r'   r9   r:   r"   r#   r(   )rB   rQ   rR   rS   rT   rU   rV   s          r3   
instrumentz*PrometheusFastApiInstrumentator.instrument   s    \ & 	t/I/I/K/K 	K.&*&D&*&D%)%B*.*L#'#>262\.2.T#'#>* 0"4!2#'#>"4,--.O"7!5]- 	 	
 	
 	
0 r5   /metricsshould_gzipendpointinclude_in_schematagskwargsc                 L     j         r                                 s S dt          dt          f fd}d}t          j                            d          r4ddlm}	 t          ||	          r|}
  |
j
        |f||d||           d	}|s|                    |||
            S )a  Exposes endpoint for metrics.

        Args:
            app: App instance. Endpoint will be added to this app. This can be
            a Starlette app or a FastAPI app. If it is a Starlette app, `tags`
            `kwargs` will be ignored.

            should_gzip: Should the endpoint return compressed data? It will
                also check for `gzip` in the `Accept-Encoding` header.
                Compression consumes more CPU cycles. In most cases it's best
                to just leave this option off since network bandwidth is usually
                cheaper than CPU cycles. Defaults to `False`.

            endpoint: Endpoint on which metrics should be exposed.

            include_in_schema: Should the endpoint show up in the documentation?

            tags (List[str], optional): If you manage your routes with tags.
                Defaults to None. Only passed to FastAPI app.

            kwargs: Will be passed to app. Only passed to FastAPI app.

        Returns:
            self: Instrumentator. Builder Pattern.
        requestr)   c                    j         }dt          j        v r"t                      }t	          j        |           rfd| j                            dd          v rIt          t          j
        t          |                              }t          |j        d<   d|j        d<   n,t          t          |                    }t          |j        d<   |S )z(Endpoint that serves Prometheus metrics.r8   gzipzAccept-EncodingrE   )contentzContent-TypezContent-Encoding)r(   r;   r<   r   r   MultiProcessCollectorheadersgetr   rd   compressr   r   )rb   ephemeral_registryresprB   r\   s      r3   r   z7PrometheusFastApiInstrumentator.expose.<locals>.metrics  s     "&)RZ77%6%8%8"23EFFF Cv)<)<=NPR)S)SSS M/:L*M*MNN   0C^,39/008J(K(KLLL/B^,Kr5   Ffastapir   )FastAPI)r^   r_   T)r2   router^   )r   rX   r   r   	importlibutil	find_specrl   rm   
isinstancerh   	add_route)rB   rQ   r\   r]   r^   r_   r`   r   route_configuredrm   fastapi_apps   ` `        r3   exposez&PrometheusFastApiInstrumentator.expose   s   F & 	t/I/I/K/K 	K	W 	 	 	 	 	 	 	 	( !>##I.. 	(''''''#w'' ('*0A PV    $(  	MMW@Q     r5   instrumentation_functionc           	      T   |D ]}|rt          j        |          rL| j                            t	          t
          t          j        gt          d         f         |                     d| j	                            t	          t
          t          j        gdf         |                     | S )av  Adds function to list of instrumentations.

        Args:
            instrumentation_function: Function
                that will be executed during every request handler call (if
                not excluded). See above for detailed information on the
                interface of the function.

        Returns:
            self: Instrumentator. Builder Pattern.
        N)
asyncioiscoroutinefunctionr:   appendr   r   r   Infor   r9   )rB   rw   funcs      r3   addz#PrometheusFastApiInstrumentator.add3  s    $ - 	 	D .t44 
/66$gl^Yt_%DE      )00Xw|nd&:;TBB   r5   c                 ^    t          j        | j        d                                          dv S )z?Checks if instrumentation should be performed based on env var.False)true1)r;   getenvr%   lower)rB   s    r3   rX   z5PrometheusFastApiInstrumentator._should_instrumentateU  s*     y*G44::<<MMr5   )rE   rE   FrF   rP   )Fr[   TN)__name__
__module____qualname__boolr   strintr
   r   rD   r   r	   floatrZ   r   r   r   rv   r   r   r|   r   r~   rX   r,   r5   r3   r   r      s        +/*/)-.3',6;27')#%&',9"'37 #' $( #'	
 (, !% 04 ,0  9 Cy !$     )4/0  
!   H !# "27>
. =J;I II I 	I
 ,0I  (eSj(9:I: 'uUCZ'89;I< 
+=I I I I\ """&15I II I 	I
  I tE#t),-.I I 
+I I I IV #+gl^U44+@%AAB$
 
 
+       DNt N N N N N Nr5   r   )#ry   rd   importlib.utilro   r;   r.   r=   enumr   typingr   r   r   r   r   r	   r
   r   prometheus_clientr   r   r   r   r   starlette.applicationsr   starlette.requestsr   starlette.responsesr   !prometheus_fastapi_instrumentatorr   ,prometheus_fastapi_instrumentator.middlewarer   r   r,   r5   r3   <module>r      s         				 				        R R R R R R R R R R R R R R R R R R R R              - , , , , , & & & & & & ( ( ( ( ( ( 5 5 5 5 5 5     
}N }N }N }N }N }N }N }N }N }Nr5   