
    `ijt                        d 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mZmZ ddlmZ ddlmZ  G d d          Zded	ed
edeee         ee         f         fdZdedefdZddddddddej        e	i fdededededed	ed
ededeeeef                  de
dedeeegdf                  fdZddddddde	i f	dededededed	ed
ede
dedeeegdf                  fd Zd!d"ddddde	i f	dededededed	ed
ede
dedeeegdf                  fd#Zd$d%ddddde	i f	dededededed	ed
ede
dedeeegdf                  fd&Zd'd(ddddde	i f	dededededed	ed
ede
dedeeegdf                  fd)Zd*e de!e         fd+Z"ddddd,d-e	i fdeded.eded/eeeef                  d0eeeef                  de
dedeeegdf                  fd1Z#dS )2a  
This module contains ready-to-use functions that can be passed on to the
instrumentator instance with the `add()` method. The idea behind this is to
make the types of metrics you want to export with the instrumentation easily
customizable. The default instrumentation function `default` can also be found
here.

If your requirements are really specific or very extensive it makes sense to
create your own instrumentation function instead of combining several functions
from this module.
    )CallableListOptionalSequenceTupleUnion)REGISTRYCollectorRegistryCounter	HistogramSummary)Request)Responsec                   B    e Zd Z	 ddedee         dededededefd	Zd
S )Info        requestresponsemethodmodified_handlermodified_statusmodified_duration#modified_duration_without_streamingc                 h    || _         || _        || _        || _        || _        || _        || _        dS )a  Creates Info object that is used for instrumentation functions.

        This is the only argument that is passed to the instrumentation functions.

        Args:
            request (Request): Python Requests request object.
            response (Response or None): Python Requests response object.
            method (str): Unmodified method of the request.
            modified_handler (str): Handler representation after processing by
                instrumentator. For example grouped to `none` if not templated.
            modified_status (str): Status code representation after processing
                by instrumentator. For example grouping into `2xx`, `3xx` and so on.
            modified_duration (float): Latency representation after processing
                by instrumentator. For example rounding of decimals. Seconds.
            modified_duration_without_streaming (float): Latency between request arrival and response starts (i.e. first chunk duration).
                Excluding the streaming duration. Defaults to 0.
        N)r   r   r   r   r   r   r   )selfr   r   r   r   r   r   r   s           }/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/prometheus_fastapi_instrumentator/metrics.py__init__zInfo.__init__   s?    8   0.!23V000    N)r   )	__name__
__module____qualname__r   r   r   strfloatr    r   r   r   r      s         69"W "W"W 8$"W 	"W
 "W "W !"W .3"W "W "W "W "W "Wr   r   should_include_handlershould_include_methodshould_include_statusreturnc                    g }g }| r*|                     d           |                     d           |r*|                     d           |                     d           |r*|                     d           |                     d           ||fS )aX  Builds up tuple with to be used label and attribute names.

    Args:
        should_include_handler (bool): Should the `handler` label be part of the metric?
        should_include_method (bool): Should the `method` label be part of the metric?
        should_include_status (bool): Should the `status` label be part of the metric?

    Returns:
        Tuple with two list elements.

        First element: List with all labels to be used.
        Second element: List with all attribute names to be used from the
            `Info` object. Done like this to enable dynamic on / off of labels.
    handlerr   r   statusr   append)r%   r&   r'   label_namesinfo_attribute_namess        r   _build_label_attribute_namesr0   ;   s    ( K 89%%%##$6777 .8$$$##H--- 78$$$##$5666,,,r   errorc                 `    t          t          | j        d         j        ddg                    S )Nr   z+Duplicated timeseries in CollectorRegistry:z,Duplicated time series in CollectorRegistry:)anymapargs__contains__)r1   s    r   _is_duplicated_time_seriesr7   a   s8    JqM&=>	
 	
  r   http_request_duration_secondsz$Duration of HTTP requests in seconds TFmetric_name
metric_docmetric_namespacemetric_subsystem!should_exclude_streaming_durationbucketsregistrycustom_labelsNc           	         |d         t          d          k    rg |t          d          }t          |||          \  |
D ],}                    |                               |           -	 rt          | |||||	          nt          | |||||	          dt          ddffd}|S # t
          $ r}t          |          s|Y d}~nd}~ww xY wdS )	a  Default metric for the Prometheus Starlette Instrumentator.

    Args:
        metric_name (str, optional): Name of the metric to be created. Must be
            unique. Defaults to "http_request_duration_seconds".

        metric_doc (str, optional): Documentation of the metric. Defaults to
            "Duration of HTTP requests in seconds".

        metric_namespace (str, optional): Namespace of all  metrics in this
            metric function. Defaults to "".

        metric_subsystem (str, optional): Subsystem of all  metrics in this
            metric function. Defaults to "".

        should_include_handler: Should the `handler` label be part of the
            metric? Defaults to `True`.

        should_include_method: Should the `method` label be part of the
            metric? Defaults to `True`.

        should_include_status: Should the `status` label be part of the
            metric? Defaults to `True`.

        should_exclude_streaming_duration: Should the streaming duration be
            excluded? Defaults to `False`.

        buckets: Buckets for the histogram. Defaults to Prometheus default.
            Defaults to default buckets from Prometheus client library.

    Returns:
        Function that takes a single parameter `Info`.
    inf)
labelnamesr?   	namespace	subsystemr@   )r?   rF   rG   r@   infor(   Nc                       j         }r j        }n j         }r- fdD             } j        |                     |           d S                     |           d S )Nc                 0    g | ]}t          |          S r$   getattr.0attribute_namerH   s     r   
<listcomp>z4latency.<locals>.instrumentation.<locals>.<listcomp>   3          & D.11     r   )r   r   labelsobserve)rH   durationlabel_valuesMETRICr/   r.   r>   s   `  r   instrumentationz latency.<locals>.instrumentation   s    -H0 2C1 )       *>     
 |,44X>>>>>x(((((r   )r#   r0   r-   r   r   
ValueErrorr7   )r:   r;   r<   r=   r%   r&   r'   r>   r?   r@   rA   keyrW   erV   r/   r.   s          `      @@@r   latencyr[   q   s   ^ r{eEll""*G*U5\\*(D 57L) )%K%  ) )3##C(((() 	&**!  FF **!  F	)$ 	)4 	) 	) 	) 	) 	) 	) 	) 	) 	)"    )!,, 	G	 	 	 	 	 4s   5AB7 7
CCChttp_request_size_byteszContent bytes of requests.c	                 b   t          |||          \  |D ],}	                    |	                               |	           -	 rt          | ||||          nt          | ||||          dt          ddffd}
|
S # t          $ r}t          |          s|Y d}~nd}~ww xY wdS )a  Record the content length of incoming requests.

    If content length is missing 0 will be assumed.

    Args:
        metric_name (str, optional): Name of the metric to be created. Must be
            unique. Defaults to "http_request_size_bytes".
        metric_doc (str, optional): Documentation of the metric. Defaults to
            "Content bytes of requests.".
        metric_namespace (str, optional): Namespace of all  metrics in this
            metric function. Defaults to "".
        metric_subsystem (str, optional): Subsystem of all  metrics in this
            metric function. Defaults to "".
        should_include_handler: Should the `handler` label be part of the
            metric? Defaults to `True`.
        should_include_method: Should the `method` label be part of the
            metric? Defaults to `True`.
        should_include_status: Should the `status` label be part of the metric?
            Defaults to `True`.

    Returns:
        Function that takes a single parameter `Info`.
    rE   rF   rG   r@   rF   rG   r@   rH   r(   Nc                      j         j                            dd          }r: fdD             } j        |                     t          |                     d S                     t          |                     d S )NContent-Lengthr   c                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z9request_size.<locals>.instrumentation.<locals>.<listcomp>&  rQ   r   )r   headersgetrR   rS   intrH   content_lengthrU   rV   r/   r.   s   `  r   rW   z%request_size.<locals>.instrumentation#  s    !\1556FJJN 4       *>     
 |,44S5H5HIIIIIs>2233333r   r0   r-   r   r   rX   r7   r:   r;   r<   r=   r%   r&   r'   r@   rA   rY   rW   rZ   rV   r/   r.   s               @@@r   request_sizerj      sO   F )E 57L) )%K%  ) )3##C((((" 	&**!  FF **!  F
	4$ 
	44 
	4 
	4 
	4 
	4 
	4 
	4 
	4 
	4    )!,, 	G	 	 	 	 	 4   >B 
B,B''B,http_response_size_byteszContent bytes of responses.c	                 b   t          |||          \  |D ],}	                    |	                               |	           -	 rt          | ||||          nt          | ||||          dt          ddffd}
|
S # t          $ r}t          |          s|Y d}~nd}~ww xY wdS )a  Record the content length of outgoing responses.

    If content length is missing 0 will be assumed.

    Args:
        metric_name (str, optional): Name of the metric to be created. Must be
            unique. Defaults to "http_response_size_bytes".

        metric_doc (str, optional): Documentation of the metric. Defaults to
            "Content bytes of responses.".

        metric_namespace (str, optional): Namespace of all  metrics in this
            metric function. Defaults to "".

        metric_subsystem (str, optional): Subsystem of all  metrics in this
            metric function. Defaults to "".

        should_include_handler: Should the `handler` label be part of the
            metric? Defaults to `True`.

        should_include_method: Should the `method` label be part of the metric?
            Defaults to `True`.

        should_include_status: Should the `status` label be part of the metric?
            Defaults to `True`.

    Returns:
        Function that takes a single parameter `Info`.
    r^   r_   rH   r(   Nc                 D     j         r6t           j         d          r! j         j                            dd          }nd}r: fdD             } j        |                     t          |                     d S                     t          |                     d S )Nrc   ra   r   c                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z:response_size.<locals>.instrumentation.<locals>.<listcomp>  rQ   r   )r   hasattrrc   rd   rR   rS   re   rf   s   `  r   rW   z&response_size.<locals>.instrumentation  s    } #	!B!B #!%!6!:!:;KQ!O!O!" 4       *>     
 |,44S5H5HIIIIIs>2233333r   rh   ri   s               @@@r   response_sizerq   7  sO   R )E 57L) )%K%  ) )3##C((((& 	&**!  FF **!  F	4$ 	44 	4 	4 	4 	4 	4 	4 	4 	4     )!,, 	G	 	 	 	 	 4rk   http_combined_size_bytesz(Content bytes of requests and responses.c	                 b   t          |||          \  |D ],}	                    |	                               |	           -	 rt          | ||||          nt          | ||||          dt          ddffd}
|
S # t          $ r}t          |          s|Y d}~nd}~ww xY wdS )a!  Record the combined content length of requests and responses.

    If content length is missing 0 will be assumed.

    Args:
        metric_name (str, optional): Name of the metric to be created. Must be
            unique. Defaults to "http_combined_size_bytes".

        metric_doc (str, optional): Documentation of the metric. Defaults to
            "Content bytes of requests and responses.".

        metric_namespace (str, optional): Namespace of all  metrics in this
            metric function. Defaults to "".

        metric_subsystem (str, optional): Subsystem of all  metrics in this
            metric function. Defaults to "".

        should_include_handler: Should the `handler` label be part of the
            metric? Defaults to `True`.

        should_include_method: Should the `method` label be part of the metric?
            Defaults to `True`.

        should_include_status: Should the `status` label be part of the metric?
            Defaults to `True`.

    Returns:
        Function that takes a single parameter `Info`.
    r^   r_   rH   r(   Nc                      j         j                            dd          } j        r6t	           j        d          r! j        j                            dd          }nd}t          |          t          |          z   }r: fdD             } j        |                     t          |                     d S                     t          |                     d S )Nra   r   rc   c                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z:combined_size.<locals>.instrumentation.<locals>.<listcomp>  rQ   r   )r   rc   rd   r   rp   re   rR   rS   )rH   
request_clresponse_clrg   rU   rV   r/   r.   s   `    r   rW   z&combined_size.<locals>.instrumentation  s    -112BAFFJ}  	!B!B  "m3778H!LL __s;/?/??N 4       *>     
 |,44S5H5HIIIIIs>2233333r   rh   ri   s               @@@r   combined_sizerx     sO   R )E 57L) )%K%  ) )3##C((((* 	&**!  FF **!  F	4$ 	44 	4 	4 	4 	4 	4 	4 	4 	4(    )!,, 	G	 	 	 	 	 4rk   http_requests_total7Total number of requests by method, status and handler.c	                 b   t          |||          \  |D ],}	                    |	                               |	           -	 rt          | ||||          nt          | ||||          dt          ddffd}
|
S # t          $ r}t          |          s|Y d}~nd}~ww xY wdS )a
  Record the number of requests.

    Args:
        metric_name (str, optional): Name of the metric to be created. Must
            be unique. Defaults to "http_requests_total".

        metric_doc (str, optional): Documentation of the metric. Defaults to
            "Total number of requests by method, status and handler.".

        metric_namespace (str, optional): Namespace of all  metrics in this
            metric function. Defaults to "".

        metric_subsystem (str, optional): Subsystem of all  metrics in this
            metric function. Defaults to "".

        should_include_handler (bool, optional): Should the `handler` label
            be part of the metric? Defaults to `True`.

        should_include_method (bool, optional): Should the `method` label be
            part of the metric? Defaults to `True`.

        should_include_status (bool, optional): Should the `status` label be
            part of the metric? Defaults to `True`.

    Returns:
        Function that takes a single parameter `Info`.
    r^   r_   rH   r(   Nc                      r, fdD             } j         |                                  d S                                  d S )Nc                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z5requests.<locals>.instrumentation.<locals>.<listcomp>H  rQ   r   )rR   inc)rH   rU   rV   r/   r.   s   ` r   rW   z!requests.<locals>.instrumentationF  sh            *>     
 |,0022222

r   )r0   r-   r   r   rX   r7   ri   s               @@@r   requestsr     sO   N )E 57L) )%K%  ) )3##C((((! 	&**!  FF **!  F		$ 		4 		 		 		 		 		 		 		 		    )!,, 	G	 	 	 	 	 4rk   
label_namec                     g }dddd}| D ]7}||v r|                     ||                    "|                     |           8|S )Nr   r   r   )r*   r+   rT   r,   )r   attribute_namesmappingitems       r   _map_label_name_valuer   Y  sn    O%#' G
  ) )7??""74=1111""4((((r   )g{Gz?g?g?g333333?皙?g      ?      ?g      ?   g      ?   g      @   g      @   g      @   g      @
      <   )r   r   r   !should_only_respect_2xx_for_highrlatency_highr_bucketslatency_lowr_bucketsc                    |d         t          d          k    rg |t          d          }|d         t          d          k    rg |t          d          }t          d D                       }	 dt          dd|z   | ||          dt          d	d
|z   | ||          dt          dd|z   | ||          t	          dd|| ||          dt	          dd||z   | ||          dt
          ddffd}	|	S # t          $ r}
t          |
          s|
Y d}
~
nd}
~
ww xY wdS )a  Contains multiple metrics to cover multiple things.

    Combines several metrics into a single function. Also more efficient than
    multiple separate instrumentation functions that do more or less the same.

    You get the following:

    * `http_requests_total` (`handler`, `status`, `method`): Total number of
        requests by handler, status and method.
    * `http_request_size_bytes` (`handler`): Total number of incoming
        content length bytes by handler.
    * `http_response_size_bytes` (`handler`): Total number of outgoing
        content length bytes by handler.
    * `http_request_duration_highr_seconds` (no labels): High number of buckets
        leading to more accurate calculation of percentiles.
    * `http_request_duration_seconds` (`handler`, `method`):
        Kepp the bucket count very low. Only put in SLIs.

    Args:
        metric_namespace (str, optional): Namespace of all  metrics in this
            metric function. Defaults to "".

        metric_subsystem (str, optional): Subsystem of all  metrics in this
            metric function. Defaults to "".

        should_only_respect_2xx_for_highr (str, optional): Should the metric
            `http_request_duration_highr_seconds` only include latencies of
            requests / responses that have a status code starting with `2`?
            Defaults to `False`.

        should_exclude_streaming_duration: Should the streaming duration be
            excluded? Defaults to `False`.

        latency_highr_buckets (tuple[float], optional): Buckets tuple for high
            res histogram. Can be large because no labels are used. Defaults to
            (0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5,
            3, 3.5, 4, 4.5, 5, 7.5, 10, 30, 60).

        latency_lowr_buckets (tuple[float], optional): Buckets tuple for low
            res histogram. Should be very small as all possible labels are
            included. Defaults to `(0.1, 0.5, 1)`.

    Returns:
        Function that takes a single parameter `Info`.
    rC   rD   c                     g | ]}|S r$   r$   )rN   rY   s     r   rP   zdefault.<locals>.<listcomp>  s    #A#A#ACC#A#A#Ar   )r   r+   r*   ry   rz   )namedocumentationrE   rF   rG   r@   )r*   r\   zContent length of incoming requests by handler. Only value of header is respected. Otherwise ignored. No percentile calculated. rl   zContent length of outgoing responses by handler. Only value of header is respected. Otherwise ignored. No percentile calculated. #http_request_duration_highr_secondszfLatency with many buckets but no API specific labels. Made for more accurate percentile calculations. )r   r   r?   rF   rG   r@   )r   r*   r8   zgLatency with only few buckets by handler. Made to be only used if aggregation by handler is important. )r   r   r?   rE   rF   rG   r@   rH   r(   Nc                      j         }r j        }n j         } fdt                    D             t                                                    z   } j        |                                   fdt          	          D             t                                                    z   } j        |                     t           j	        j
                            dd                                fdt                    D             t                                                    z   } j        r^t           j        d          rI j        |                     t           j        j
                            dd                               n j        |                     d           r j                            d          r                    |            fdt          
          D             t                                                    z   } j        |                     |           d S )	Nc                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z4default.<locals>.instrumentation.<locals>.<listcomp>  3       " n--  r   c                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z4default.<locals>.instrumentation.<locals>.<listcomp>  r   r   ra   r   c                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z4default.<locals>.instrumentation.<locals>.<listcomp>   r   r   rc   2c                 0    g | ]}t          |          S r$   rK   rM   s     r   rP   z4default.<locals>.instrumentation.<locals>.<listcomp>0  r   r   )r   r   r   listvaluesrR   r~   rS   re   r   rc   rd   r   rp   r   
startswith)rH   rT   rU   IN_SIZELATENCY_HIGHRLATENCY_LOWROUT_SIZETOTALrA   in_size_nameslatency_lower_namesout_size_namesr>   r   total_label_namess   `  r   rW   z default.<locals>.instrumentation  s   -H0 2C1   &;<M&N&N   ]))++,,-L EL,'++---   &;M&J&J   ]))++,,-L GNL)11DL(,,-=qAABB     &;N&K&K   ]))++,,-L } :	!B!B :.66-112BAFFGG     .66q9994 08L8W8W9 9 0 %%h///   &;<O&P&P   ]))++,,-L  L.66x@@@@@r   )r#   tupler   r   r   r   rX   r7   )r<   r=   r   r>   r   r   r@   rA   additional_label_namesrW   rZ   r   r   r   r   r   r   r   r   r   s     ``   `   @@@@@@@@@r   defaultr   h  sr   Z R E%LL00 F"7 Fu FB5<<//D!5DuU||D ##A#A=#A#A#ABBw

 &S(+AA&&
 
 
 %*- %'==&&
 
 
 &+- &(>>&&
 
 
 "6C *&&

 

 


 !0P )*-CC&&
 
 
)	A$ )	A4 )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	A )	AV    )!,, 	G	 	 	 	 	 4s   ?BD 
D>#D99D>)$__doc__typingr   r   r   r   r   r   prometheus_clientr	   r
   r   r   r   starlette.requestsr   starlette.responsesr   r   boolr"   r0   rX   r7   DEFAULT_BUCKETSr#   dictr[   rj   rq   rx   r   r   r   r   r   r$   r   r   <module>r      s  
 
 D C C C C C C C C C C C C C C C V V V V V V V V V V V V V V & & & & & & ( ( ( ( ( (#W #W #W #W #W #W #W #WL#- #-#-  #- 49d3i 	#- #- #- #-L	j 	T 	 	 	 	" 7<#'"&"&.3+4+D"*k kkk k 	k
 !k  k  k (,k eE3J'(k  k k hvt|$%k k k k^ 12#'"&"&"*U UUU U 	U
 !U  U  U  U U hvt|$%U U U Ur 23#'"&"&"*_ ___ _ 	_
 !_  _  _  _ _ hvt|$%_ _ _ _F 2@#'"&"&"*b bbb b 	b
 !b  b  b  b b hvt|$%b b b bL -O#'"&"&"*X XXX X 	X
 !X  X  X  X X hvt|$%X X X Xve S	      .3.3:. 9F"*=T TTT (,T (,	T
 $E%*$56T8 #5#459T:  ;T< =T> hvt|$%?T T T T T Tr   