o
    ٰiE                     @   s  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 d dl	m
Z
 d dl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mZ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! e!rd dl m"Z" d dl m#Z# d dl m$Z$ d dl m%Z% d dl&m'Z'm(Z(m)Z) e#de$de"f dZ*dZ+dZ,d<ddZ-d=ddZ.d>ddZ/G d d! d!eZ0d?d#d$Z1	%	&	'	&	(	&		)d@d*d+Z2d%d&d'd&de3fd,d-Z4d'd&d.d/de3fd0d1Z5dAd5d6Z6dBd:d;Z7dS )C    N)deepcopy)datetime	timedeltatimezone)environ)continue_trace)OP)should_send_default_pii)TransactionSource)AnnotatedValuecapture_internal_exceptionsensure_integration_enabledevent_from_exceptionloggerTimeoutThreadreraise)Integration)_filter_headers)TYPE_CHECKING)Any)TypeVar)Callable)Optional)EventProcessorEventHintF.)boundi  g     @@
init_errorreturnc                    s   t t d fdd}|S )Nargsr   kwargsr   c                     s   t  }t D t    t }|r-t|r-t||j	dddd\}}t j
||d n| d }t|tr;t|}t|}t 
| W d    n1 sNw   Y   | i |S )N
aws_lambdaFtypehandledclient_options	mechanismhint   )
sentry_sdk
get_clientr   get_isolation_scopeclear_breadcrumbssysexc_infoallr   optionscapture_event
isinstancestrjsonloads_event_from_error_json)r    r!   clientr1   sentry_eventr*   
error_infor    V/home/ubuntu/.local/lib/python3.10/site-packages/sentry_sdk/integrations/aws_lambda.pysentry_init_error,   s&   



z+_wrap_init_error.<locals>.sentry_init_errorr    r   r!   r   r   r   )r   AwsLambdaIntegration)r   r@   r>   r=   r?   _wrap_init_error+   s   rC   handlerc                    s0   t  										d	 fdd}|S )
N	aws_eventr   aws_contextr    r!   r   c                    s  t  }|t}|d u r | |g|R i |S t| tr-t| dkr-| d }t| }n| }d}t|ts8i }| }t 	 }	d }
t
 N |	  |	t||| |	d|jdd  |dkrp|	dd |	d| |jr|tkr|t t }t||t |	t  d	}
|
  W d    n1 sw   Y  |d
i }t|tsi }t|tj|jtjtjd}t j|| |ddd zRz" | |g|R i |W W |
r|
   W  d    W  d    S  t!y
   t"# }t$||j%dddd\}}t j&||d t'|  Y nw W |
r|
   n	|
r|
   w w W d    n1 s(w   Y  W d    d S W d    d S 1 sAw   Y  d S )Nr+   r   
aws_region:   batch_requestT
batch_size)isolation_scopecurrent_scopeheaders)opnamesourceorigin)rE   rF   )custom_sampling_contextr"   Fr#   r&   r)   )(r,   r-   get_integrationrB   r5   listlendictget_remaining_time_in_millisrL   r   r/   add_event_processor_make_request_event_processorset_taginvoked_function_arnsplittimeout_warningTIMEOUT_WARNING_BUFFERMILLIS_TO_SECONDSr   get_current_scopestartgetr   r   FUNCTION_AWSfunction_namer
   	COMPONENTrR   start_transactionstop	Exceptionr0   r1   r   r3   r4   r   )rE   rF   r    r!   r:   integrationrequest_datarK   configured_timescopetimeout_threadwaiting_timerN   transactionr1   r;   r*   rD   r>   r?   sentry_handlerJ   s   



"
:

 1$z%_wrap_handler.<locals>.sentry_handler)
rE   r   rF   r   r    r   r!   r   r   r   )	functoolswraps)rD   rr   r>   rq   r?   _wrap_handlerI   s   iru   c                  C   s^   t  " t } | t}|d ur|   W d    d S W d    d S 1 s(w   Y  d S N)r   r,   r-   rT   rB   flush)r:   rj   r>   r>   r?   _drain_queue   s   

"rx   c                   @   s<   e Zd ZdZde ZddeddfddZedd	d
ZdS )rB   r"   zauto.function.Fr^   r   Nc                 C   s
   || _ d S rv   )r^   )selfr^   r>   r>   r?   __init__   s   
zAwsLambdaIntegration.__init__c                     s  t  } | std d S t| dstd d S t| d}|rX| j 									d fd
d}|| _| j									dfdd}|| _| jdfdd}|| _d S t| jj	| j_	| j  fdd}|| _ddd}|| jj
| j_
|| jj| j_d S )NzfNot running in AWS Lambda environment, AwsLambdaIntegration disabled (could not find bootstrap module)handle_event_requestzjNot running in AWS Lambda environment, AwsLambdaIntegration disabled (could not find handle_event_request)handle_http_requestrequest_handlerr   r    r!   r   c                       t | }  | g|R i |S rv   ru   r}   r    r!   old_handle_event_requestr>   r?   sentry_handle_event_request      zDAwsLambdaIntegration.setup_once.<locals>.sentry_handle_event_requestc                    r~   rv   r   r   )old_handle_http_requestr>   r?   sentry_handle_http_request   r   zCAwsLambdaIntegration.setup_once.<locals>.sentry_handle_http_requestc                        t    | i |S rv   rx   r    r!   )old_to_jsonr>   r?   sentry_to_json      z7AwsLambdaIntegration.setup_once.<locals>.sentry_to_jsonc                    s    t |} | |g|R i |S rv   r   )lambda_runtime_clientr}   r    r!   r   r>   r?   r     s   fr   c                    s   d fdd}|S )Nr    r   r!   r   c                     r   rv   r   r   r   r>   r?   inner  r   zKAwsLambdaIntegration.setup_once.<locals>._wrap_post_function.<locals>.innerrA   r>   )r   r   r>   r   r?   _wrap_post_function  s   z<AwsLambdaIntegration.setup_once.<locals>._wrap_post_function)r}   r   r    r   r!   r   r   r   rA   )r   r   r   r   )get_lambda_bootstrapr   warninghasattrr{   r|   to_jsonrC   LambdaRuntimeClientpost_init_errorpost_invocation_resultpost_invocation_error)lambda_bootstrappre_37r   r   r   r   r>   )r   r   r   r?   
setup_once   sj   




zAwsLambdaIntegration.setup_once)Fr   N)	__name__
__module____qualname__
identifierrR   boolrz   staticmethodr   r>   r>   r>   r?   rB      s    
rB   Optional[Any]c                  C   s^   dt jv r
t jd S dt jv r-t jd } t| dr#t| jdr#| jjS t| dr+| jS | S d S )N	bootstrap__main__awslambdaricmain)r0   modulesr   r   r   )moduler>   r>   r?   r   !  s   




r   rE   r   rF   configured_timeoutr   c                    s4   t tj}|f							d fd	d
}|S )Nr;   r   r*   r   
start_timer   r   Optional[Event]c                    sT     }| }| di } j j j j||d|d< t | j jd|d< | 	di }dv r:d |d< t
 |d	< d
v rKd
 |d< dv rWtd |d< t r| di }	d}|d u rki }|	d}	|	d urz|d|	 |	d}
|
d ur|d|
 dv r	dd|d< n	dd rt |d< t|| d< | S )Nextra)re   function_versionr\   aws_request_idexecution_duration_in_millisremaining_time_in_millislambda)url	log_group
log_streamzcloudwatch logsrequest
httpMethodmethodr   queryStringParametersquery_stringrN   useridentityuserArnidsourceIp
ip_addressbody data)rX   
setdefaultre   r   r\   r   _get_cloudwatch_logs_urllog_group_namelog_stream_namerc   _get_urlr   r	   r   removed_because_raw_datar   )r;   r*   r   remaining_time_in_milisexec_durationr   r   	user_infor   r   iprF   rE   r   r>   r?   event_processorI  sP   





z6_make_request_event_processor.<locals>.event_processor)r;   r   r*   r   r   r   r   r   )r   nowr   utc)rE   rF   r   r   r   r>   r   r?   rZ   D  s   >rZ   c                 C   s`   |  dd }|  d}|d u ri }| dd }| dd }|r*|r*|r*d|||S d|jS )NpathrN   HostzX-Forwarded-Protoz	{}://{}{}zawslambda:///{})rc   formatre   )rE   rF   r   rN   hostprotor>   r>   r?   r     s   
r   r   r   c              
   C   sd   d}t dd}dj|drdnd|| j| j|tdd	 |t	t
jtd
d	 |d}|S )z
    Generates a CloudWatchLogs console URL based on the context object

    Arguments:
        aws_context {Any} -- context from lambda handler

    Returns:
        str -- AWS Console URL to logs.
    z%Y-%m-%dT%H:%M:%SZ
AWS_REGIONr   zhttps://console.{domain}/cloudwatch/home?region={region}#logEventViewer:group={log_group};stream={log_stream};start={start_time};end={end_time}zcn-zamazonaws.cnzaws.amazon.comr+   )seconds   )domainregionr   r   r   end_time)r   rc   r   
startswithr   r   r   strftimer   r   r   r   )rF   r   formatstringr   r   r>   r>   r?   r     s   
r   formatted_tb	list[str]list[dict[str, Any]]c                 C   sV   g }| D ]$}t d| }|r(| \}}}t|}||||d d d d d q|S )Nz File "(.+)", line (\d+), in (.+))filenamefunctionlinenovarspre_contextcontext_linepost_context)rematchstripgroupsintappend)r   framesframer   	file_nameline_number	func_namer>   r>   r?   _parse_formatted_traceback  s$   r   
error_jsondict[str, Any]r   c              
   C   s@   dd|  d|  ddt|  dg iddd	d
gid}|S )a9  
    Converts the error JSON from AWS Lambda into a Sentry error event.
    This is not a full fletched event, but better than nothing.

    This is an example of where AWS creates the error JSON:
    https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/2.2.1/awslambdaric/bootstrap.py#L479
    errorvalues	errorTypeerrorMessager   
stackTracer"   Fr#   )r$   value
stacktracer(   )level	exception)rc   r   )r   eventr>   r>   r?   r9     s    	
r9   )r   r   r   r   )rD   r   r   r   r   )r   r   )rE   r   rF   r   r   r   r   r   )r   r   r   r   )r   r   r   r   )8rs   r7   r   r0   copyr   r   r   r   osr   r,   sentry_sdk.apir   sentry_sdk.constsr   sentry_sdk.scoper	   sentry_sdk.tracingr
   sentry_sdk.utilsr   r   r   r   r   r   r   sentry_sdk.integrationsr   $sentry_sdk.integrations._wsgi_commonr   typingr   r   r   r   r   sentry_sdk._typesr   r   r   r   r_   r`   rC   ru   rx   rB   r   rZ   r6   r   r   r   r9   r>   r>   r>   r?   <module>   sV    $	


n

`#
F
