
    Oǻie5                        d Z ddlmZ ddlmZmZmZmZmZ ddl	Z	erddl
mZ ddlmZ ddlmZ ddlmZ d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(d Z)d!Z*d"Z+d#Z,d$Z-d%Z.d&Z/d'Z0 G d( d)e      Z1 G d* d+e      Z2 G d, d-e      Z3 G d. d/e      Z4 G d0 d1e      Z5 G d2 d3      Z6d4ed5   d6e7fd7Z8d8ed9   fd:Z9y);a  
OpenTelemetry semantic convention attributes for Redis.

This module provides constants and helper functions for building OTel attributes
according to the semantic conventions for database clients.

Reference: https://opentelemetry.io/docs/specs/semconv/database/redis/
    )Enum)TYPE_CHECKINGAnyDictOptionalUnionN)ConnectionPool)AsyncDatabase)ConnectionPoolInterface)SyncDatabasez	db.systemzdb.namespacezdb.operation.namezdb.response.status_codezdb.stored_procedure.namez
error.typeznetwork.peer.addressznetwork.peer.portzserver.addresszserver.portzdb.client.connection.pool.namezdb.client.connection.statezdb.client.connection.namezdb.client.geofailover.fail_fromzdb.client.geofailover.fail_tozdb.client.geofailover.reasonzredis.client.libraryzredis.client.connection.pubsubz$redis.client.connection.close.reasonz$redis.client.connection.notificationz%redis.client.operation.retry_attemptszredis.client.operation.blockingz%redis.client.pubsub.message.directionzredis.client.pubsub.channelzredis.client.pubsub.shardedzredis.client.errors.internalzredis.client.errors.categoryzredis.client.stream.namezredis.client.consumer_groupzredis.client.csc.resultzredis.client.csc.reasonc                       e Zd ZdZdZy)ConnectionStateidleusedN)__name__
__module____qualname__IDLEUSED     \/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/redis/observability/attributes.pyr   r   C   s    DDr   r   c                       e Zd ZdZdZy)PubSubDirectionpublishreceiveN)r   r   r   PUBLISHRECEIVEr   r   r   r   r   H   s    GGr   r   c                       e Zd ZdZdZy)	CSCResulthitmissN)r   r   r   HITMISSr   r   r   r    r    M   s    
CDr   r    c                       e Zd ZdZdZy)	CSCReasonfullinvalidationN)r   r   r   FULLINVALIDATIONr   r   r   r&   r&   R   s    D!Lr   r&   c                       e Zd ZdZdZy)GeoFailoverReason	automaticmanualN)r   r   r   	AUTOMATICMANUALr   r   r   r,   r,   W   s    IFr   r,   c                      e Zd ZdZe	 	 	 d(dee   dee   dee   deee	f   fd       Z
e	 	 	 	 	 	 	 d)deeeef      d	ee   d
ee   dee   dee   dee   dee   deee	f   fd       Ze	 	 	 	 d*dee   dee   dee   dee   deee	f   f
d       Ze	 	 d+dee   dee   deee	f   fd       Ze	 	 d+dedee   dee   deee	f   fd       Ze	 	 	 d(dee   dee   dee   deee	f   fd       Ze	 	 	 d(dee   d ee   d!ee   deee	f   fd"       Zed#ed$   d%ed$   d!edeee	f   fd&       Ze	 d,dedededefd'       Zy)-AttributeBuilderzY
    Helper class to build OTel semantic convention attributes for Redis operations.
    Nserver_addressserver_portdb_namespacereturnc                     t         dt        dt        j                   i}| 	| |t        <   |	||t
        <   |t        |      |t        <   |S )a*  
        Build base attributes common to all Redis operations.

        Args:
            server_address: Redis server address (FQDN or IP)
            server_port: Redis server port
            db_namespace: Redis database index

        Returns:
            Dictionary of base attributes
        redisz
redis-py:v)	DB_SYSTEMREDIS_CLIENT_LIBRARYr8   __version__SERVER_ADDRESSSERVER_PORTstrDB_NAMESPACE)r3   r4   r5   attrss       r   build_base_attributesz&AttributeBuilder.build_base_attributesa   s_    $ w Ju/@/@.A"B!

 %$2E.!"!,E+#"%l"3E,r   command_name
batch_sizenetwork_peer_addressnetwork_peer_portstored_procedure_nameretry_attemptsis_blockingc                     i }| :t        | t              r| j                  dd      } | j                         |t        <   |	||t
        <   |	||t        <   |	||t        <   ||dkD  r	||t        <   |	||t        <   |S )aw  
        Build attributes for a Redis operation (command execution).

        Args:
            command_name: Redis command name (e.g., 'GET', 'SET', 'MULTI'), can be str or bytes
            batch_size: Number of commands in batch (for pipelines/transactions)
            network_peer_address: Resolved peer address
            network_peer_port: Peer port number
            stored_procedure_name: Lua script name or SHA1 digest
            retry_attempts: Number of retry attempts made
            is_blocking: Whether the operation is a blocking command

        Returns:
            Dictionary of operation attributes
        zutf-8replace)errorsr   )

isinstancebytesdecodeupperDB_OPERATION_NAMENETWORK_PEER_ADDRESSNETWORK_PEER_PORTDB_STORED_PROCEDURE_NAME%REDIS_CLIENT_OPERATION_RETRY_ATTEMPTSREDIS_CLIENT_OPERATION_BLOCKING)rB   rC   rD   rE   rF   rG   rH   r@   s           r   build_operation_attributesz+AttributeBuilder.build_operation_attributes   s    2 !##,.+22792M'3'9'9';E#$+*>E&'('8E#$ ,.CE*+%.1*<;IE78"5@E12r   	pool_nameconnection_stateconnection_name	is_pubsubc                     t         j                         }| 	| |t        <   ||j                  |t        <   |	||t
        <   |	||t        <   |S )ay  
        Build attributes for connection pool metrics.

        Args:
            pool_name: Unique connection pool name
            connection_state: Connection state ('idle' or 'used')
            is_pubsub: Whether this is a PubSub connection
            connection_name: Unique connection name

        Returns:
            Dictionary of connection pool attributes
        )r2   rA   DB_CLIENT_CONNECTION_POOL_NAMEvalueDB_CLIENT_CONNECTION_STATEREDIS_CLIENT_CONNECTION_PUBSUBDB_CLIENT_CONNECTION_NAME)rW   rX   rY   rZ   r@   s        r   build_connection_attributesz,AttributeBuilder.build_connection_attributes   sa    & !1 F F H 4=E01'0@0F0FE,- 4=E01&/>E+,r   
error_typeis_internalc                 F   i }| | j                   j                  |t        <   t        | d      r | j                  | j                  |t
        <   n	d|t
        <   t        | d      r*| j                  | j                  j                  |t        <   n	d|t        <   |	||t        <   |S )z
        Build error attributes.

        Args:
            is_internal: Whether the error is internal (e.g., timeout, network error)
            error_type: The exception that occurred

        Returns:
            Dictionary of error attributes
        status_codeerrorrb   other)
	__class__r   
ERROR_TYPEhasattrre   DB_RESPONSE_STATUS_CODErb   r]   REDIS_CLIENT_ERROR_CATEGORYREDIS_CLIENT_ERROR_INTERNAL)rb   rc   r@   s      r   build_error_attributesz'AttributeBuilder.build_error_attributes   s     !#! * 4 4 = =E* 
M2**61;1G1G-.18-.z<0Z5J5J5V5?5J5J5P5P125<12"1<E-.r   	directionchannelshardedc                     t         j                         }| j                  |t        <   |	||t        <   |	||t
        <   |S )a.  
        Build attributes for a PubSub message.

        Args:
            direction: Message direction ('publish' or 'receive')
            channel: Pub/Sub channel name
            sharded: True if sharded Pub/Sub channel

        Returns:
            Dictionary of PubSub message attributes
        )r2   rA   r]   %REDIS_CLIENT_PUBSUB_MESSAGE_DIRECTIONREDIS_CLIENT_PUBSUB_CHANNELREDIS_CLIENT_PUBSUB_SHARDED)ro   rp   rq   r@   s       r   build_pubsub_message_attributesz0AttributeBuilder.build_pubsub_message_attributes   sH    " !1 F F H7@3418E-.18E-.r   stream_nameconsumer_groupconsumer_namec                 Z    t         j                         }| 	| |t        <   |	||t        <   |S )a   
        Build attributes for a streaming operation.

        Args:
            stream_name: Name of the stream
            consumer_group: Name of the consumer group
            consumer_name: Name of the consumer

        Returns:
            Dictionary of streaming attributes
        )r2   rA   REDIS_CLIENT_STREAM_NAMEREDIS_CLIENT_CONSUMER_GROUP)rw   rx   ry   r@   s       r   build_streaming_attributesz+AttributeBuilder.build_streaming_attributes  s9    " !1 F F H".9E*+%1?E-.r   resultreasonc                     t         j                         }| 	| |t        <   ||j                  |t        <   ||j                  |t
        <   |S )a\  
        Build attributes for a Client Side Caching (CSC) operation.

        Args:
            pool_name: Connection pool name (used only for csc_items metric)
            result: CSC result ('hit' or 'miss')
            reason: Reason for CSC eviction ('full' or 'invalidation')

        Returns:
            Dictionary of CSC attributes
        )r2   rA   r\   r]   REDIS_CLIENT_CSC_RESULTREDIS_CLIENT_CSC_REASON)rW   r~   r   r@   s       r   build_csc_attributesz%AttributeBuilder.build_csc_attributes4  sR    " !1 F F H 4=E01-3\\E)*-3\\E)*r   	fail_fromr   r
   fail_toc                     t         j                         }t        |       |t        <   t        |      |t        <   |j
                  |t        <   |S )a	  
        Build attributes for a geo failover.

        Args:
            fail_from: Database failed from
            fail_to: Database failed to
            reason: Reason for the failover

        Returns:
            Dictionary of geo failover attributes
        )r2   rA   get_db_nameDB_CLIENT_GEOFAILOVER_FAIL_FROMDB_CLIENT_GEOFAILOVER_FAIL_TOr]   DB_CLIENT_GEOFAILOVER_REASON)r   r   r   r@   s       r   build_geo_failover_attributesz.AttributeBuilder.build_geo_failover_attributesR  sF    " !1 F F H1<Y1G-./:7/C+,.4ll*+r   c                     |  d| d| S )a  
        Build a unique connection pool name.

        Args:
            server_address: Redis server address
            server_port: Redis server port
            db_namespace: Redis database index

        Returns:
            Unique pool name in format "address:port/db"
        :/r   )r3   r4   r5   s      r   build_pool_namez AttributeBuilder.build_pool_namek  s    " !!;-q??r   )NNN)NNNNNNN)NNNN)NN)r   )r   r   r   __doc__staticmethodr   r>   intr   r   rA   r   rM   boolrV   r   ra   	Exceptionrn   r   rv   r}   r    r&   r   r,   r   r   r   r   r   r2   r2   \   s:    (,%)&* c] sm 
c3h	 @ 48$(.2+//3(,&*/uS%Z01/SM/ 'sm/ $C=	/
  (}/ !/ d^/ 
c3h/ /b #'6:)-$(	 C= "?3  "#  D>	 
 
c3h   D *.&*#Y'#d^# 
c3h# #J  "&"&"# $ 
c3h	 6 %)(,'+c]   } 
c3h	 4 #'&*&*C=# # 
c3h	 : 8967 " 
c3h	 0  @@@ @ 
	@ @r   r2   pool)r   r	   r6   c                     | j                   j                  dd      }| j                   j                  dd      }t        | dd      }|r
| d| d| S | d| S )	a  
    Get a short string representation of a connection pool for observability.

    This provides a concise pool identifier suitable for use as a metric attribute,
    in the format: host:port_uniqueID (matching go-redis format)

    Args:
        pool: Connection pool instance

    Returns:
        Short pool name in format "host:port_uniqueID"

    Example:
        >>> pool = ConnectionPool(host='localhost', port=6379, db=0)
        >>> get_pool_name(pool)
        'localhost:6379_a1b2c3d4'
    hostunknownporti  _pool_id r   _)connection_kwargsgetgetattr)r   r   r   pool_ids       r   get_pool_namer     so    $ !!%%fi8D!!%%fd3D dJ+Gqay))qr   databaser   c                     | j                   j                         d   }| j                   j                         d   }| j                  }| d| d| S )z
    Get a short string representation of a database for observability.

    Args:
        database: Database instance

    Returns:
        Short database name in format "{host}:{port}/{weight}"
    r   r   r   r   )clientget_connection_kwargsweight)r   r   r   r   s       r   r   r     sR     ??0026:D??0026:D__FV1TF!F8$$r   ):r   enumr   typingr   r   r   r   r   r8   redis.asyncio.connectionr	   redis.asyncio.multidb.databaser
   redis.connectionr   redis.multidb.databaser   r9   r?   rP   rk   rS   ri   rQ   rR   r<   r=   r\   r^   r`   r   r   r   r:   r_   $REDIS_CLIENT_CONNECTION_CLOSE_REASON$REDIS_CLIENT_CONNECTION_NOTIFICATIONrT   rU   rs   rt   ru   rm   rl   r{   r|   r   r   r   r   r    r&   r,   r2   r>   r   r   r   r   r   <module>r      sb    < < 7<83 	' 3 5  
 . '  " "B 9 7  #D  ? =  . !A 'M $'M $(O %"C (O %; ; < < 5 ; 3 3 d 
d 
 
" "
 
`@ `@F	 IJ  s  <%% ?@ %r   