
    ng\j9_                     R   S r SSKrSSKrSSKJr  SSKJrJrJrJ	r	  \(       a  SSK
Jr  SSKJr  SSKJr  SSKJr  SS	KJrJrJrJrJrJrJrJrJr  SS
KJrJr  SSKJ r J!r!  \RD                  " \#5      r$ SSK%J&r&  Sr' " S S\5      r, " S S5      r-g! \( a    Sr'Sr)Sr*Sr&Sr+ N(f = f)z
OpenTelemetry metrics collector for redis-py.

This module defines and manages all metric instruments according to
OTel semantic conventions for database clients.
    N)Enum)TYPE_CHECKINGCallableOptionalUnion)ConnectionPool)AsyncDatabase)ConnectionPoolInterface)SyncDatabase)	$REDIS_CLIENT_CONNECTION_CLOSE_REASON$REDIS_CLIENT_CONNECTION_NOTIFICATIONAttributeBuilderConnectionState	CSCReason	CSCResultGeoFailoverReasonPubSubDirectionget_pool_name)MetricGroup
OTelConfig)deprecated_argsdeprecated_function)MeterTFc                   $    \ rS rSrSrSrSrSrSrg)CloseReason0   a  
Enum representing the reason why a Redis client connection was closed.

Values:
    APPLICATION_CLOSE: The connection was closed intentionally by the application
        (for example, during normal shutdown or explicit cleanup).
    ERROR: The connection was closed due to an unexpected error
        (for example, network failure or protocol error).
    HEALTHCHECK_FAILED: The connection was closed because a health check
        or liveness check for the connection failed.
application_closeerrorhealthcheck_failed N)	__name__
__module____qualname____firstlineno____doc__APPLICATION_CLOSEERRORHEALTHCHECK_FAILED__static_attributes__r        V/home/edenadmin/noVNC/venv/lib/python3.13/site-packages/redis/observability/metrics.pyr   r   0   s    
 ,E-r*   r   c                      \ rS rSrSrSrSrS\S\4S jr	SQS
 jr
SQS jrSQS jrSQS jrSQS jrSQS jrSQS jr       SRS\\   S\\   S\\   S\\   S\\   S\\   S\\   4S jjrS\S\S\S\S\4
S jrS\S   S\S   S\4S jr SSS \S!\S"\SS	4S# jjr\" S$S%S&9S'\SS	4S( j5       rS'\SS	4S) jr S \SS	4S* jr!S+\S,   S-\"SS	4S. jr#S \S-\"SS	4S/ jr$\%" S0/S1S2S39         STS4\S-\"S\\   S\\   S5\\   S0\\   S\\   S\\   S\\   S\\   S6\\   SS	4S7 jj5       r&  SUS8\\'   S\\   SS	4S9 jjr(S:\S\S;\SS	4S< jr)S \SS	4S= jr*  SUS>\+S?\\   S@\\   SS	4SA jjr,\%" SB/SCS2S39   SVSD\"SE\\   SF\\   SB\\   SS	4
SG jj5       r- SWSH\\.   SS	4SI jjr/ SWSJ\S\\0   SS	4SK jjr1SL\SS	4SM jr2\3S\"4SN j5       r4S\4SO jr5SPr6g	)XRedisMetricsCollectorB   aP  
Collects and records OpenTelemetry metrics for Redis operations.

This class manages all metric instruments and provides methods to record
various Redis operations including connection pool events, command execution,
and cluster-specific operations.

Args:
    meter: OpenTelemetry Meter instance
    config: OTel configuration object
zredis-pyz1.0.0meterconfigc                    [         (       d  [        S5      eXl        X l        [	        5       U l        [        R                  U R                  R                  ;   a  U R                  5         [        R                  U R                  R                  ;   a  U R                  5         [        R                  U R                  R                  ;   a  U R                  5         [        R                  U R                  R                  ;   a  U R                  5         [        R                   U R                  R                  ;   a  U R#                  5         [        R$                  U R                  R                  ;   a  U R'                  5         [        R(                  U R                  R                  ;   a  U R+                  5         [,        R/                  S5        g )NzROpenTelemetry API is not installed. Install it with: pip install opentelemetry-apiz!RedisMetricsCollector initialized)OTEL_AVAILABLEImportErrorr/   r0   r   attr_builderr   
RESILIENCYmetric_groups_init_resiliency_metricsCOMMAND_init_command_metricsCONNECTION_BASIC_init_connection_basic_metricsCONNECTION_ADVANCED!_init_connection_advanced_metricsPUBSUB_init_pubsub_metrics	STREAMING_init_streaming_metricsCSC_init_csc_metricsloggerinfo)selfr/   r0   s      r+   __init__RedisMetricsCollector.__init__R   s:   ~A 
 
,. !!T[[%>%>>))+$++";";;&&(''4;;+D+DD//1**dkk.G.GG224!:!::%%'  DKK$=$==((*??dkk777""$78r*   returnNc                     U R                   R                  SSSS9U l        U R                   R                  SSSS9U l        U R                   R                  SS	S
S9U l        g)zInitialize resiliency metrics.zredis.client.errorsz{error}z`A counter of all errors (both returned to the user and handled internally in the client library)nameunitdescriptionz&redis.client.maintenance.notificationsz{notification}z,Tracks server-side maintenance notificationsz"redis.client.geofailover.failoversz{geofailover}z6Total count of failovers happened using MultiDbClient.N)r/   create_counterclient_errorsmaintenance_notificationsgeo_failoversrF   s    r+   r7   .RedisMetricsCollector._init_resiliency_metricsv   sv    !ZZ66&z 7 
 *.)B)B9!F *C *
& "ZZ665 P 7 
r*   c                 <   U R                   R                  SSSU R                  R                  S9U l        U R                   R                  SSSS9U l        U R                   R                  S	S
SS9U l        SU l	        U R                   R                  SSSS9U l
        g)z$Initialize basic connection metrics.z db.client.connection.create_timeszTime to create a new connectionrL   rM   rN   #explicit_bucket_boundaries_advisoryz'redis.client.connection.relaxed_timeoutz{relaxation}z@Counts up for relaxed timeout, counts down for unrelaxed timeoutrK   zredis.client.connection.handoffz	{handoff}zIConnections that have been handed off (e.g., after a MOVING notification)Nzdb.client.connection.count{connection}z4Number of connections currently in the pool by state)r/   create_histogramr0   buckets_connection_create_timeconnection_create_timecreate_up_down_counterconnection_relaxed_timeoutrO   connection_handoffconnection_countconnection_count_updownrS   s    r+   r;   4RedisMetricsCollector._init_connection_basic_metrics   s    &*jj&A&A39040Z0Z	 'B '
# +/***K*K:Z +L +
' #'**";";2c #< #
 !% (,zz'H'H-N (I (
$r*   c                     U R                   R                  SSSS9U l        U R                   R                  SSSU R                  R
                  S9U l        U R                   R                  S	S
SS9U l        g)z'Initialize advanced connection metrics.zdb.client.connection.timeoutsz	{timeout}zaThe number of connection timeouts that have occurred trying to obtain a connection from the pool.rK   zdb.client.connection.wait_timerV   z/Time to obtain an open connection from the poolrW   zredis.client.connection.closedrY   z"Total number of closed connectionsN)r/   rO   connection_timeoutsrZ   r0   buckets_connection_wait_timeconnection_wait_timeconnection_closedrS   s    r+   r=   7RedisMetricsCollector._init_connection_advanced_metrics   s    #'::#<#<0{ $= $
  %)JJ$?$?1I040X0X	 %@ %
! "&!:!:1< "; "
r*   c                 n    U R                   R                  SSSU R                  R                  S9U l        g)z0Initialize command execution metric instruments.zdb.client.operation.durationrV   zCommand execution durationrW   N)r/   rZ   r0   buckets_operation_durationoperation_durationrS   s    r+   r9   +RedisMetricsCollector._init_command_metrics   s4    "&**"="=/4040V0V	 #> #
r*   c                 D    U R                   R                  SSSS9U l        g)z%Initialize PubSub metric instruments.zredis.client.pubsub.messagesz	{message}z&Tracks published and received messagesrK   N)r/   rO   pubsub_messagesrS   s    r+   r?   *RedisMetricsCollector._init_pubsub_metrics   s'    #zz88/@  9  
r*   c                 n    U R                   R                  SSSU R                  R                  S9U l        g)z(Initialize Streaming metric instruments.zredis.client.stream.lagrV   zkEnd-to-end lag per message, showing how stale are the messages when the application starts processing them.rW   N)r/   rZ   r0   "buckets_stream_processing_duration
stream_lagrS   s    r+   rA   -RedisMetricsCollector._init_streaming_metrics   s6    **55* F040^0^	 6 
r*   c                     U R                   R                  SSSS9U l        U R                   R                  SSSS9U l        U R                   R                  SS	S
S9U l        g)z8Initialize Client Side Caching (CSC) metric instruments.zredis.client.csc.requestsz	{request}z)The total number of requests to the cacherK   zredis.client.csc.evictionsz
{eviction}z#The total number of cache evictionszredis.client.csc.network_savedByz,The total number of bytes saved by using CSCN)r/   rO   csc_requestscsc_evictionscsc_network_savedrS   s    r+   rC   'RedisMetricsCollector._init_csc_metrics   su     JJ55,C 6 
 "ZZ66-= 7 
 "&!:!:1F "; "
r*   server_addressserver_portnetwork_peer_addressnetwork_peer_port
error_typeretry_attemptsis_internalc                 6   [        U S5      (       d  gU R                  R                  UUS9nUR                  U R                  R	                  UUUS95        UR                  U R                  R                  UUS95        U R                  R                  SUS9  g)a?  
Record error count

Args:
    server_address: Server address
    server_port: Server port
    network_peer_address: Network peer address
    network_peer_port: Network peer port
    error_type: Error type
    retry_attempts: Retry attempts
    is_internal: Whether the error is internal (e.g., timeout, network error)
rP   Nrz   r{   )r|   r}   r   )r~   r      
attributes)hasattrr4   build_base_attributesupdatebuild_operation_attributesbuild_error_attributesrP   add)	rF   rz   r{   r|   r}   r~   r   r   attrss	            r+   record_error_count(RedisMetricsCollector.record_error_count   s    , t_--!!77)# 8 
 	88%9"3- 9 	
 	44%' 5 	
 	qU3r*   maint_notificationc                     [        U S5      (       d  gU R                  R                  UUS9nUR                  U R                  R	                  UUS95        XV[
        '   U R                  R                  SUS9  g)z
Record maintenance notification count

Args:
    server_address: Server address
    server_port: Server port
    network_peer_address: Network peer address
    network_peer_port: Network peer port
    maint_notification: Maintenance notification
rQ   Nr   )r|   r}   r   r   )r   r4   r   r   r   r   rQ   r   )rF   rz   r{   r|   r}   r   r   s          r+   record_maint_notification_count5RedisMetricsCollector.record_maint_notification_count  s    $ t899!!77)# 8 

 	88%9"3 9 	
 7I23&&**1*?r*   	fail_from)r   r	   fail_toreasonc                     [        U S5      (       d  gU R                  R                  UUUS9nU R                  R	                  SUS9$ )z
Record geo failover

Args:
    fail_from: Database failed from
    fail_to: Database failed to
    reason: Reason for the failover
rR   N)r   r   r   r   r   )r   r4   build_geo_failover_attributesrR   r   )rF   r   r   r   r   s        r+   record_geo_failover)RedisMetricsCollector.record_geo_failoverC  sW     t_--!!?? @ 
 !!%%aE%::r*   	pool_nameconnection_statecounterc                     [        U S5      (       d  gU R                  R                  UUS9nU R                  R	                  X4S9  g)z
Record a connection count change for a single state.

Args:
    pool_name: Connection pool name
    connection_state: State to update (IDLE or USED)
    counter: Number to add (positive) or subtract (negative)
ra   N)r   r   r   )r   r4   build_connection_attributesra   r   )rF   r   r   r   r   s        r+   record_connection_count-RedisMetricsCollector.record_connection_count]  sO     t677!!==- > 
 	$$(((Cr*   z{Connection count is now tracked via record_connection_count(). This functionality will be removed in the next major versionz7.4.0)r   versioncallbackc                     [         R                  U R                  R                  ;  a  gU R                  R                  SSSU/S9U l        g)z
Initialize observable gauge for connection count metric.

Args:
    callback: Callback function to retrieve connection counts
Nz%db.client.connection.count.deprecatedrY   zThe number of connections that are currently in state described by the state attribute (deprecated - use db.client.connection.count instead)rL   rM   rN   	callbacks)r   r:   r0   r6   r/   create_observable_gauger`   rF   r   s     r+   init_connection_count+RedisMetricsCollector.init_connection_countt  sO     ''t{{/H/HH
 !%

 B B8ej !C !
r*   c                     [         R                  U R                  R                  ;  a  U R                  (       d  gU R
                  R                  SSSU/S9U l        g)zv
Initialize observable gauge for CSC items metric.

Args:
    callback: Callback function to retrieve CSC items count
Nzredis.client.csc.itemsz{item}z5The total number of cached responses currently storedr   )r   rB   r0   r6   	csc_itemsr/   r   r   s     r+   init_csc_items$RedisMetricsCollector.init_csc_items  sL     ??$++";";;DNN;;)Oj	 < 
r*   c                     [        U S5      (       d  gU R                  R                  US9nU R                  R	                  SUS9  g)zO
Record a connection timeout event.

Args:
    pool_name: Connection pool name
rd   Nr   r   r   )r   r4   r   rd   r   rF   r   r   s      r+   record_connection_timeout/RedisMetricsCollector.record_connection_timeout  sG     t233!!==	=R  $$Q5$9r*   connection_pool)r
   r   duration_secondsc                     [        U S5      (       d  gU R                  R                  [        U5      S9nU R                  R                  X#S9  g)z
Record time taken to create a new connection.

Args:
    connection_pool: Connection pool implementation
    duration_seconds: Creation time in seconds
r\   Nr   r   )r   r4   r   r   r\   record)rF   r   r   r   s       r+   record_connection_create_time3RedisMetricsCollector.record_connection_create_time  sR     t566!!==#O4 > 
 	##**+;*Nr*   c                     [        U S5      (       d  gU R                  R                  US9nU R                  R	                  X#S9  g)z
Record time taken to obtain a connection from the pool.

Args:
    pool_name: Connection pool name
    duration_seconds: Wait time in seconds
rf   Nr   r   )r   r4   r   rf   r   )rF   r   r   r   s       r+   record_connection_wait_time1RedisMetricsCollector.record_connection_wait_time  sF     t344!!==	=R!!(()9(Lr*   
batch_sizezXThe batch_size argument is no longer used and will be removed in the next major version.z7.2.1)args_to_warnr   r   command_namedb_namespaceis_blockingc           
      z   [        U S5      (       d  gU R                  R                  U5      (       d  gU R                  R	                  UUUS9nUR                  U R                  R                  UUU	U
US95        UR                  U R                  R                  US95        U R                  R                  X,S9  g)aP  
Record command execution duration.

Args:
    command_name: Redis command name (e.g., 'GET', 'SET', 'MULTI')
    duration_seconds: Execution time in seconds
    server_address: Redis server address
    server_port: Redis server port
    db_namespace: Redis database index
    batch_size: Number of commands in batch (for pipelines/transactions)
    error_type: Error type if operation failed
    network_peer_address: Resolved peer address
    network_peer_port: Peer port number
    retry_attempts: Number of retry attempts made
    is_blocking: Whether the operation is a blocking command
rk   N)rz   r{   r   )r   r|   r}   r   r   r~   r   )
r   r0   should_track_commandr4   r   r   r   r   rk   r   )rF   r   r   rz   r{   r   r   r~   r|   r}   r   r   r   s                r+   record_operation_duration/RedisMetricsCollector.record_operation_duration  s    F t122 {{//== !!77)#% 8 
 	88)%9"3-' 9 	
 	44% 5 	

 	&&'7&Jr*   close_reasonc                    [        U S5      (       d  gU R                  R                  5       nU(       a  UR                  U[        '   UR                  U R                  R                  US95        U R                  R                  SUS9  g)z
Record a connection closed event.

Args:
    close_reason: Reason for closing (e.g. 'error', 'application_close')
    error_type: Error type if closed due to error
rg   Nr   r   r   )	r   r4   r   valuer   r   r   rg   r   )rF   r   r~   r   s       r+   record_connection_closed.RedisMetricsCollector.record_connection_closed  s     t011!!==?:F:L:LE6744% 5 	
 	""1"7r*   connection_namerelaxedc                     [        U S5      (       d  gU R                  R                  US9nX$[        '   U R                  R                  U(       a  SOSUS9  g)z
Record a connection timeout relaxation event.

Args:
    connection_name: Connection name
    maint_notification: Maintenance notification type
    relaxed: True to count up (relaxed), False to count down (unrelaxed)
r^   Nr   r   r   )r   r4   r   r   r^   r   )rF   r   r   r   r   s        r+   !record_connection_relaxed_timeout7RedisMetricsCollector.record_connection_relaxed_timeout7  sT     t9::!!===X6H23''++AbU+Sr*   c                     [        U S5      (       d  gU R                  R                  US9nU R                  R	                  SUS9  g)zq
Record a connection handoff event (e.g., after MOVING notification).

Args:
    pool_name: Connection pool name
r_   Nr   r   r   )r   r4   r   r_   r   r   s      r+   record_connection_handoff/RedisMetricsCollector.record_connection_handoffL  sG     t122!!==	=R##A%#8r*   	directionchannelshardedc                     [        U S5      (       d  gU R                  R                  UUUS9nU R                  R	                  SUS9  g)z
Record a PubSub message (published or received).

Args:
    direction: Message direction ('publish' or 'receive')
    channel: Pub/Sub channel name
    sharded: True if sharded Pub/Sub channel
rn   N)r   r   r   r   r   )r   r4   build_pubsub_message_attributesrn   r   )rF   r   r   r   r   s        r+   record_pubsub_message+RedisMetricsCollector.record_pubsub_message^  sU     t.//!!AA B 

 	  u 5r*   consumer_namez[The consumer_name argument is no longer used and will be removed in the next major version.lag_secondsstream_nameconsumer_groupc                     [        U S5      (       d  gU R                  R                  UUS9nU R                  R	                  XS9  g)z
Record the lag of a streaming message.

Args:
    lag_seconds: Lag in seconds
    stream_name: Stream name
    consumer_group: Consumer group name
    consumer_name: Consumer name
rr   N)r   r   r   )r   r4   build_streaming_attributesrr   r   )rF   r   r   r   r   r   s         r+   record_streaming_lag*RedisMetricsCollector.record_streaming_lagx  sL    * t\**!!<<#) = 
 	{=r*   resultc                     [        U S5      (       d  gU R                  R                  US9nU R                  R	                  SUS9  g)z]
Record a Client Side Caching (CSC) request.

Args:
    result: CSC result ('hit' or 'miss')
rv   N)r   r   r   )r   r4   build_csc_attributesrv   r   )rF   r   r   s      r+   record_csc_request(RedisMetricsCollector.record_csc_request  sF     t^,,!!66f6EaE2r*   countc                     [        U S5      (       d  gU R                  R                  US9nU R                  R	                  XS9  g)zt
Record a Client Side Caching (CSC) eviction.

Args:
    count: Number of evictions
    reason: Reason for eviction
rw   N)r   r   )r   r4   r   rw   r   )rF   r   r   r   s       r+   record_csc_eviction)RedisMetricsCollector.record_csc_eviction  sD     t_--!!66f6Eu7r*   bytes_savedc                     [        U S5      (       d  gU R                  R                  5       nU R                  R	                  XS9  g)zt
Record the number of bytes saved by using Client Side Caching (CSC).

Args:
    bytes_saved: Number of bytes saved
rx   Nr   )r   r4   r   rx   r   )rF   r   r   s      r+   record_csc_network_saved.RedisMetricsCollector.record_csc_network_saved  s@     t011!!668"";"Ar*   c                  ,    [         R                  " 5       $ )z_
Get monotonic time for duration measurements.

Returns:
    Current monotonic time in seconds
)time	monotonicr    r*   r+   monotonic_time$RedisMetricsCollector.monotonic_time  s     ~~r*   c                 <    SU R                    SU R                   S3$ )NzRedisMetricsCollector(meter=z	, config=))r/   r0   rS   s    r+   __repr__RedisMetricsCollector.__repr__  s    -djj\4;;-qQQr*   )r4   rP   r0   rg   r`   ra   r\   r_   r^   rd   rf   rw   r   rx   rv   rR   rQ   r/   rk   rn   rr   )rI   N)NNNNNNN)r   )	NNNNNNNNN)NN)NNN)N)7r!   r"   r#   r$   r%   
METER_NAMEMETER_VERSIONr   r   rG   r7   r;   r=   r9   r?   rA   rC   r   strint	Exceptionboolr   r   r   r   r   r   r   r   r   r   r   r   floatr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r)   r    r*   r+   r-   r-   B   s   
 JM"9e "9Z "9H
( 
D
*



0 )-%).2+/*.(,&*,4 ,4 c],4 'sm	,4
 $C=,4 Y',4 !,4 d^,4\"@"@ "@ "	"@
 "@  "@H;89; 67; "	;< 	DD *D 	D
 
D. G


 



0

 

(:3 :4 :OJKO  O 
	O(MM  M 
	M( "^i )-%)&*$(*..2+/(,&*;K;K  ;K !	;K
 c];K sm;K SM;K Y';K 'sm;K $C=;K !;K d^;K 
;K
;K~ /3*.8{+8 Y'8 
	86TT  T 	T
 
T*99 
9* "&"&	6"6 #6 $	6
 
64 %&l &*(,'+>> c]> !	>
  }> 
>
>: '+3#3 
3& '+88 #8 
	8$BB 
B$  E    R# Rr*   r-   ).r%   loggingr   enumr   typingr   r   r   r   redis.asyncio.connectionr   redis.asyncio.multidb.databaser	   redis.connectionr
   redis.multidb.databaser   redis.observability.attributesr   r   r   r   r   r   r   r   r   redis.observability.configr   r   redis.utilsr   r   	getLoggerr!   rD   opentelemetry.metricsr   r2   r3   Counter	HistogramUpDownCounterr   r-   r    r*   r+   <module>r     s       ; ;7<83
 
 
 ? <			8	$	+N.$ .$U
R U
R5  NGIEMs   5B B&%B&