
    /JfuP                         d dl Z d dlZd dlZd dlZd dlmZmZmZ d dlm	Z
  ej        e          Z G d d          Z G d d          Z G d d	          Z G d
 de          Z G d de          Z G d d          Z G d d          ZdS )    N)ensure_bytesensure_unicodeurlparse)EXCEPTION_MAPc                   (    e Zd Zg dZd Zd Zd ZdS )Monitor)zbefore-parameter-buildzrequest-createdzresponse-receivedz
after-callzafter-call-errorc                 "    || _         || _        dS )zAbstraction for monitoring clients API calls

        :param adapter: An adapter that takes event emitter events
            and produces monitor events

        :param publisher: A publisher for generated monitor events
        N)_adapter
_publisher)selfadapter	publishers      V/home/alex/cs2snipeproduction/venv/lib/python3.11/site-packages/botocore/monitoring.py__init__zMonitor.__init__!   s      #    c                 P    | j         D ]}|                    || j                   dS )z(Register an event emitter to the monitorN)_EVENTS_TO_REGISTERregister_lastcapture)r   event_emitterevent_to_registers      r   registerzMonitor.register,   s?    !%!9 	I 	I''(94<HHHH	I 	Ir   c                     	 | j                             ||          }|r| j                            |           dS dS # t          $ r)}t
                              d||d           Y d}~dS d}~ww xY w)zCaptures an incoming event from the event emitter

        It will feed an event emitter event to the monitor's adaptor to create
        a monitor event and then publish that event to the monitor's publisher.
        z:Exception %s raised by client monitor in handling event %sT)exc_infoN)r
   feedr   publish	Exceptionloggerdebug)r   
event_namepayloadmonitor_eventes        r   r   zMonitor.capture1   s    
	 M..z7CCM 7''666667 7 	 	 	LLL	          	s   7= 
A0A++A0N)__name__
__module____qualname__r   r   r   r    r   r   r   r      sV          	$ 	$ 	$I I I
    r   r   c                   d    e Zd Zej        f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S )MonitorEventAdapterc                     || _         dS )zAdapts event emitter events to produce monitor events

        :type time: callable
        :param time: A callable that produces the current time
        N)_time)r   times     r   r   zMonitorEventAdapter.__init__E   s     


r   c                 8     |                      |          di |S )a  Feed an event emitter event to generate a monitor event

        :type emitter_event_name: str
        :param emitter_event_name: The name of the event emitted

        :type emitter_payload: dict
        :param emitter_payload: The payload to associated to the event
            emitted

        :rtype: BaseMonitorEvent
        :returns: A monitor event based on the event emitter events
            fired
        r'   )_get_handler)r   emitter_event_nameemitter_payloads      r   r   zMonitorEventAdapter.feedM   s)     5t  !344GGGGGr   c                     t          | d|                    d          d                             dd          z             S )N_handle_.r   -_)getattrsplitreplace)r   r    s     r   r.   z MonitorEventAdapter._get_handler]   sA    *z//44Q7??SIII
 
 	
r   c                 r    t          |j        j        |j        |                                           |d<   d S )Nservice	operation	timestampcurrent_api_call_event)APICallEventservice_model
service_id	wire_name_get_current_time)r   modelcontextkwargss       r   _handle_before_parameter_buildz2MonitorEventAdapter._handle_before_parameter_buildb   s?    ,8'2o,,..-
 -
 -
()))r   c                     |j         }|d                             |                                           }|j        |_        |j        |_        ||d<   d S )Nr>   )r=   current_api_call_attempt_event)rE   new_api_call_attemptrC   headersrequest_headersurl)r   requestrF   rE   new_attempt_events        r   _handle_request_createdz+MonitorEventAdapter._handle_request_createdi   s_    /#$


)?)?)A)A

B
B 	 -4O) '4E0111r   c                     |                     d          }|                     |          |_        |A|d         d         |_        |d         d         |_        |                    d          |_        n||_        |S )NrI   ResponseMetadataHTTPStatusCodeHTTPHeadersError)pop_get_latencylatencyhttp_status_coderesponse_headersgetparsed_errorwire_exception)r   parsed_responserE   	exceptionrF   attempt_events         r   _handle_response_receivedz-MonitorEventAdapter._handle_response_receivedr   s      $DEE $ 1 1- @ @&-<".. M* .="..M* *9)<)<W)E)EM&&+4M(r   c                 z    |d                              dd          |d         _        |                     |          S )NrR   MaxAttemptsReachedFr>   )r[   retries_exceeded_complete_api_call)r   rE   parsedrF   s       r   _handle_after_callz&MonitorEventAdapter._handle_after_call   sA    =C>

#"E
*
* 	(): &&w///r   c                 l    |                      |          |d         _        |                     |          S Nr>   )_is_retryable_exceptionrd   re   )r   rE   r_   rF   s       r   _handle_after_call_errorz,MonitorEventAdapter._handle_after_call_error   s9     "99)DD 	$	

&&w///r   c                 R    t          |t          t          d                             S )NGENERAL_CONNECTION_ERROR)
isinstancetupleRETRYABLE_EXCEPTIONS)r   r_   s     r   rj   z+MonitorEventAdapter._is_retryable_exception   s(    u12LMNN
 
 	
r   c                 d    |                     d          }|                     |          |_        |S ri   )rV   rW   rX   )r   rE   
call_events      r   re   z&MonitorEventAdapter._complete_api_call   s0    [[!9::
!..z::
r   c                 :    |                                  |j        z
  S N)rC   r=   r   events     r   rW   z MonitorEventAdapter._get_latency   s    %%''%/99r   c                 J    t          |                                 dz            S )Ni  )intr+   r   s    r   rC   z%MonitorEventAdapter._get_current_time   s    4::<<$&'''r   N)r$   r%   r&   r,   r   r   r.   rG   rP   ra   rg   rk   rj   re   rW   rC   r'   r   r   r)   r)   D   s         I    H H H 
 
 


 
 
F F F  "0 0 00 0 0
 
 

  
: : :( ( ( ( (r   r)   c                        e Zd Zd Zd Zd ZdS )BaseMonitorEventc                 0    || _         || _        || _        dS )a  Base monitor event

        :type service: str
        :param service: A string identifying the service associated to
            the event

        :type operation: str
        :param operation: A string identifying the operation of service
            associated to the event

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds from when the event began
        Nr:   )r   r;   r<   r=   s       r   r   zBaseMonitorEvent.__init__   s     ""r   c                 0    | j         j         d| j        dS )N())	__class__r$   __dict__ry   s    r   __repr__zBaseMonitorEvent.__repr__   s     .)>>DM>>>>r   c                 P    t          || j                  r| j        |j        k    S dS )NF)rn   r   r   )r   others     r   __eq__zBaseMonitorEvent.__eq__   s*    eT^,, 	3=EN22ur   N)r$   r%   r&   r   r   r   r'   r   r   r{   r{      sA        # # #$? ? ?    r   r{   c                   ,     e Zd Z	 	 	 d fd	Zd Z xZS )r?   NFc                     t                                          |||           || _        || _        |g | _        || _        dS )a  Monitor event for a single API call

        This event corresponds to a single client method call, which includes
        every HTTP requests attempt made in order to complete the client call

        :type service: str
        :param service: A string identifying the service associated to
            the event

        :type operation: str
        :param operation: A string identifying the operation of service
            associated to the event

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds from when the event began

        :type latency: int
        :param latency: The time in milliseconds to complete the client call

        :type attempts: list
        :param attempts: The list of APICallAttempts associated to the
            APICall

        :type retries_exceeded: bool
        :param retries_exceeded: True if API call exceeded retries. False
            otherwise
        r:   N)superr   rX   attemptsrd   )r   r;   r<   r=   rX   r   rd   r   s          r   r   zAPICallEvent.__init__   sY    H 	yI 	 	
 	
 	
  DM 0r   c                 r    t          | j        | j        |          }| j                            |           |S )zInstantiates APICallAttemptEvent associated to the APICallEvent

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds to associate to the
            APICallAttemptEvent
        r:   )APICallAttemptEventr;   r<   r   append)r   r=   r`   s      r   rJ   z!APICallEvent.new_api_call_attempt   sA     ,LDNi
 
 
 	]+++r   )NNF)r$   r%   r&   r   rJ   __classcell__r   s   @r   r?   r?      sX         +1 +1 +1 +1 +1 +1Z      r   r?   c                   .     e Zd Z	 	 	 	 	 	 	 d fd	Z xZS )r   Nc                     t                                          |||           || _        || _        || _        || _        || _        |	| _        |
| _        dS )a  Monitor event for a single API call attempt

        This event corresponds to a single HTTP request attempt in completing
        the entire client method call.

        :type service: str
        :param service: A string identifying the service associated to
            the event

        :type operation: str
        :param operation: A string identifying the operation of service
            associated to the event

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds from when the HTTP request
            started

        :type latency: int
        :param latency: The time in milliseconds to complete the HTTP request
            whether it succeeded or failed

        :type url: str
        :param url: The URL the attempt was sent to

        :type http_status_code: int
        :param http_status_code: The HTTP status code of the HTTP response
            if there was a response

        :type request_headers: dict
        :param request_headers: The HTTP headers sent in making the HTTP
            request

        :type response_headers: dict
        :param response_headers: The HTTP headers returned in the HTTP response
            if there was a response

        :type parsed_error: dict
        :param parsed_error: The error parsed if the service returned an
            error back

        :type wire_exception: Exception
        :param wire_exception: The exception raised in sending the HTTP
            request (i.e. ConnectionError)
        r:   N)	r   r   rX   rM   rY   rL   rZ   r\   r]   )r   r;   r<   r=   rX   rM   rY   rL   rZ   r\   r]   r   s              r   r   zAPICallAttemptEvent.__init__   sl    r 	yI 	 	
 	
 	
  0. 0(,r   )NNNNNNN)r$   r%   r&   r   r   r   s   @r   r   r      s^         B- B- B- B- B- B- B- B- B- B-r   r   c                      e Zd ZdZdZdZdZdZddddZ e	j
        d	           e	j
        d
          dZg 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&S )'CSMSerializer         i   XAmznRequestIdXAmzRequestIdXAmzId2)zx-amzn-requestidzx-amz-request-idz
x-amz-id-2zSAWS4-HMAC-SHA256 Credential=(?P<access_key>\w+)/\d+/(?P<signing_region>[a-z0-9-]+)/zAWS (?P<access_key>\w+):)v4s3)r;   r<   r=   r   rX   rd   rM   rL   rY   rZ   r\   r]   c                 >    |                      |           || _        dS )zSerializes monitor events to CSM (Client Side Monitoring) format

        :type csm_client_id: str
        :param csm_client_id: The application identifier to associate
            to the serialized events
        N)_validate_client_idcsm_client_idr   r   s     r   r   zCSMSerializer.__init__d  s&     	  ///*r   c                 l    t          |          | j        k    rt          d| d| j         d          d S )Nz&The value provided for csm_client_id: z exceeds the maximum length of z characters)len_MAX_CLIENT_ID_LENGTH
ValueErrorr   s     r   r   z!CSMSerializer._validate_client_idn  s^    } :::Q Q Q)-)CQ Q Q   ;:r   c                    |                      |          }|                     |          }||d<   | j        D ]4}t          ||d          }| t          | d|z             |||           5t	          t          j        |d                    S )zSerializes a monitor event to the CSM format

        :type event: BaseMonitorEvent
        :param event: The event to serialize to bytes

        :rtype: bytes
        :returns: The CSM serialized form of the event
        TypeN_serialize_)
event_type),:)
separators)_get_base_event_dict_get_event_type_SERIALIZEABLE_EVENT_PROPERTIESr6   r   jsondumps)r   rv   
event_dictr   attrvalues         r   	serializezCSMSerializer.serializeu  s     ..u55
))%00
'
68 	 	DE4..E 3md233:*    DJzjIIIJJJr   c                     d| j         dS )N   )VersionClientId)r   ru   s     r   r   z"CSMSerializer._get_base_event_dict  s    *
 
 	
r   c                     ||d<   d S )NServicer'   )r   r;   r   rF   s       r   _serialize_servicez CSMSerializer._serialize_service  s     '
9r   c                     ||d<   d S )NApir'   )r   r<   r   rF   s       r   _serialize_operationz"CSMSerializer._serialize_operation  s    %
5r   c                     ||d<   d S )N	Timestampr'   )r   r=   r   rF   s       r   _serialize_timestampz"CSMSerializer._serialize_timestamp  s    "+
;r   c                 j    t          |          |d<   |r|                     ||d                    d S d S )NAttemptCount)r   _add_fields_from_last_attempt)r   r   r   rF   s       r   _serialize_attemptsz!CSMSerializer._serialize_attempts  sG    %(]]
>" 	I..z8B<HHHHH	I 	Ir   c                 B   |j         r>|                     |j                   }|||d<   |                     |j                   |d<   |j        
|j        |d<   |j        |                     |j        |d           |j        |                     |j        |d           d S d S )NRegion	UserAgentFinalHttpStatusCodeApiCall)rL   _get_region_get_user_agentrY   r\   _serialize_parsed_errorr]   _serialize_wire_exception)r   r   last_attemptregions       r   r   z+CSMSerializer._add_fields_from_last_attempt  s    ' 	 %%l&BCCF!'-
8$&*&:&:,' 'J{# (40<0MJ,-$0(():y   &2**+Z     32r   c                 :    |dk    r||d<   d S |dk    r||d<   d S d S )Nr   LatencyApiCallAttemptAttemptLatencyr'   )r   rX   r   r   s       r   _serialize_latencyz CSMSerializer._serialize_latency  sB    ""$+Jy!!!++++2J'((( ,+r   c                     |rdnd|d<   d S )Nr   r   MaxRetriesExceededr'   )r   rd   r   rF   s       r   _serialize_retries_exceededz)CSMSerializer._serialize_retries_exceeded  s     1A+G11a
'(((r   c                 4    t          |          j        |d<   d S )NFqdn)r   netloc)r   rM   r   rF   s       r   _serialize_urlzCSMSerializer._serialize_url  s    %c]]1
6r   c                     |                      |          |d<   |                     |          r|                     |          |d<   |                     |          }|||d<   d|v r|d         |d<   d S d S )Nr   	AccessKeyr   zX-Amz-Security-TokenSessionToken)r   
_is_signed_get_access_keyr   )r   rL   r   rF   r   s        r   _serialize_request_headersz(CSMSerializer._serialize_request_headers  s     #'"6"6"G"G
;???++ 	L&*&:&:?&K&KJ{#!!/22#)Jx !_44)8&*J~&&& 54r   c                     ||d<   d S )NHttpStatusCoder'   )r   rY   r   rF   s       r   _serialize_http_status_codez)CSMSerializer._serialize_http_status_code  s     (8
#$$$r   c                 b    | j                                         D ]\  }}||v r||         ||<   d S rt   )"_RESPONSE_HEADERS_TO_EVENT_ENTRIESitems)r   rZ   r   rF   headerentrys         r   _serialize_response_headersz)CSMSerializer._serialize_response_headers  sL     "DJJLL 	= 	=MFE)))$4V$<
5!	= 	=r   c                     |dk    rdnd}|                      |d         | j                  ||dz   <   |                      |d         | j                  ||dz   <   d S )Nr   Final CodeAwsExceptionMessageAwsExceptionMessage)	_truncate_MAX_ERROR_CODE_LENGTH_MAX_MESSAGE_LENGTH)r   r\   r   r   rF   field_prefixs         r   r   z%CSMSerializer._serialize_parsed_error  su     #-	"9"9wwr48NN $"=5
 5

<.01 <@>>#T%=<
 <

<"77888r   c                     |dk    rdnd}|                      |j        j        | j                  ||dz   <   |                      t	          |          | j                  ||dz   <   d S )Nr   r   r   SdkExceptionSdkExceptionMessage)r   r   r$   _MAX_EXCEPTION_CLASS_LENGTHstrr   )r   r]   r   r   rF   r   s         r   r   z'CSMSerializer._serialize_wire_exception  sy     #-	"9"9wwr48NN$-t/O5
 5

<.01 <@>>!9<
 <

<"77888r   c                 b    t          |t                    rdS t          |t                    rdS d S )Nr   r   )rn   r?   r   ru   s     r   r   zCSMSerializer._get_event_type  s<    e\** 	$9233 	$##	$ 	$r   c                     |                      |          }|                     |          \  }}|                    d          S )N
access_key)_get_auth_value_get_auth_matchgroup)r   rL   auth_valr5   
auth_matchs        r   r   zCSMSerializer._get_access_key  s@    ''88,,X66:---r   c                     |                      |          sd S |                     |          }|                     |          \  }}|dk    rd S |                    d          S )Nr   signing_region)r   r   r   r   )r   rL   r  signature_versionr  s        r   r   zCSMSerializer._get_region  sl    // 	4''88(,(<(<X(F(F%:$$4 0111r   c                 z    |                      t          |                    dd                    | j                  S )Nz
User-Agentr   )r   r   r[   _MAX_USER_AGENT_LENGTHr   rL   s     r   r   zCSMSerializer._get_user_agent  s9    ~~?..|R@@AA'
 
 	
r   c                 
    d|v S NAuthorizationr'   r  s     r   r   zCSMSerializer._is_signed
  s    /11r   c                 ,    t          |d                   S r
  )r   r  s     r   r   zCSMSerializer._get_auth_value  s    oo>???r   c                 ~    | j                                         D ]"\  }}|                    |          }|r||fc S #dS )N)NN)_AUTH_REGEXSr   match)r   r  r  regexr  s        r   r   zCSMSerializer._get_auth_match  sZ    (,(9(?(?(A(A 	0 	0$uKK))E 0(%////0zr   c                 x    t          |          |k    r&t                              d||           |d |         S |S )Nz6Truncating following value to maximum length of %s: %s)r   r   r   )r   text
max_lengths      r   r   zCSMSerializer._truncate  sH    t99z!!LLK  
 $$r   N)&r$   r%   r&   r   r   r   r  r   r   recompiler  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r'   r   r   r   r   B  s       "%  ,+* *& bj/
 

 bj455 L' ' '#+ + +  K K K(
 
 
( ( (& & &, , ,I I I
  *3 3 3H H H
2 2 2  8 8 8
= = =	
 	
 	
	
 	
 	
$ $ $. . .
2 2 2
 
 
2 2 2@ @ @      r   r   c                       e Zd ZdZd Zd ZdS )SocketPublisheri    c                 4    || _         ||f| _        || _        dS )a)  Publishes monitor events to a socket

        :type socket: socket.socket
        :param socket: The socket object to use to publish events

        :type host: string
        :param host: The host to send events to

        :type port: integer
        :param port: The port on the host to send events to

        :param serializer: The serializer to use to serialize the event
            to a form that can be published to the socket. This must
            have a `serialize()` method that accepts a monitor event
            and return bytes
        N)_socket_address_serializer)r   sockethostport
serializers        r   r   zSocketPublisher.__init__%  s$    " t%r   c                 
   | j                             |          }t          |          | j        k    r0t                              dt          |          | j                   dS | j                            || j                   dS )zPublishes a specified monitor event

        :type event: BaseMonitorEvent
        :param event: The monitor event to be sent
            over the publisher's socket to the desired address.
        z`Serialized event of size %s exceeds the maximum length allowed: %s. Not sending event to socket.N)	r  r   r   _MAX_MONITOR_EVENT_LENGTHr   r   r  sendtor  )r   rv   serialized_events      r   r   zSocketPublisher.publish:  s      +55e<<  4#AAALL<$%%.	   F,dm<<<<<r   N)r$   r%   r&   r!  r   r   r'   r   r   r  r  "  s8         (& & &*= = = = =r   r  )r   loggingr  r,   botocore.compatr   r   r   botocore.retryhandlerr   rp   	getLoggerr$   r   r   r)   r{   r?   r   r   r  r'   r   r   <module>r(     s     				  B B B B B B B B B B G G G G G G		8	$	$) ) ) ) ) ) ) )X]( ]( ]( ]( ]( ]( ]( ](@       89 9 9 9 9# 9 9 9xC- C- C- C- C-* C- C- C-L] ] ] ] ] ] ] ]@(= (= (= (= (= (= (= (= (= (=r   