U
    ShX:                     @   s   d Z 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m	Z	m
Z
 ddlmZ ddlZddlmZmZ ddlmZmZmZ eeZG dd dZded
ddZded
ddZded
ddZdddedddZdeedddZe Z dS )z
Error monitoring decorators and middleware for automatic error detection and notification.
This module provides decorators to automatically monitor API calls and system functions for errors.
    N)DictAnyOptionalCallableUnion)datetime)capture_exceptioncapture_message) send_critical_error_notificationsend_api_failure_notificationsend_system_alertc                   @   sZ   e Zd ZdZedeeeedddZedeeedddZedee	ed
ddZ
dS )ErrorMonitorz4Error monitoring class with decorators and utilitiesTapi_namecriticalinclude_request_datainclude_response_datac                    s   t t d fdd}|S )a  
        Decorator to monitor API calls and send notifications on failure
        
        Args:
            api_name: Name of the API (OpenAI, Jira, Azure, etc.)
            critical: Whether this API call is critical (sends email notification)
            include_request_data: Whether to include request data in notifications
            include_response_data: Whether to include response data in notifications
        funcreturnc                    s"   t   fdd}|S )Nc                     s0  t   }d}d }d }d }z| r8t| d dr8| d j}n"d|krJ|d }nd|krZ|d }r| rrt| d d nd |rdd | D nd d}td	  d
|  | |}t   | }td  d ||t	 
 dd |W S  tjjk
r }	 zt   | }t|	}
t|	drl|	jd k	rl|	jj}rlz|	jjrP|	j nd }W n   ddi}Y nX t|	 |||||d rt ||
|||d  W 5 d }	~	X Y n| tk
r* }	 z\t   | }t|	}
t|	 |||t|	jd rtd  |
 |||d|	d  W 5 d }	~	X Y nX d S )Nunknownr   urlendpointi  c                 S   s"   i | ]\}}|t |d d qS )N   )str).0kv r   @/var/www/html/testcasegenerator.evdpl.com/utils/error_monitor.py
<dictcomp><   s      zUErrorMonitor.monitor_api_call.<locals>.decorator.<locals>.wrapper.<locals>.<dictcomp>)argskwargszMaking API call to : zAPI call successful: info)r   r   execution_time	timestamplevelcontextresponseerrorzUnable to parse response)r   r   status_coder%   request_dataresponse_data)r   r   error_messager,   r.   r-   )r   r   r%   r-   
error_typeZ
API_ERROR_)r   r   r%   r-   r0   r/   r)   	exception)timehasattrr   r   itemsloggerr$   r	   r   utcnow	isoformatrequests
exceptionsRequestExceptionr*   r,   contentjsonr   r   	Exceptiontype__name__r
   )r!   r"   
start_timer   r-   r.   r,   resultr%   er/   )r   r   r   r   r   r   r   wrapper'   s    




	zAErrorMonitor.monitor_api_call.<locals>.decorator.<locals>.wrapper	functoolswrapsr   rD   r   r   r   	decorator&   s    rz0ErrorMonitor.monitor_api_call.<locals>.decoratorr   )r   r   r   r   rJ   r   r   r   monitor_api_call   s    uzErrorMonitor.monitor_api_call)function_nameinclude_contextalert_on_failurec                    s   t t d fdd}|S )a8  
        Decorator to monitor critical system functions
        
        Args:
            function_name: Name of the function for logging/notification
            include_context: Whether to include function context in notifications
            alert_on_failure: Whether to send email alerts on failure
        r   c                    s    t   fdd}|S )Nc            	   
      s   t   }d }z~r<t| |r*t| ng t  d}td  | |}t   | }t	d d|t  dd |W S  t
k
r } zpt   | }t|}|t|jt  d}|r|| t||  rtdd	 d
| ||d  W 5 d }~X Y nX d S )N)rM   Z
args_countZkwargs_keysr&   zExecuting critical function: z)Critical function executed successfully: r$   )rM   r%   r&   r'   )rM   r%   r0   r&   ZCRITICAL_FUNCTION_ERRORzCritical function '
' failed: r1   )r3   lenlistkeysr   r7   r8   r6   r$   r	   r>   r   r?   r@   updater   r
   )	r!   r"   rA   r)   rB   r%   rC   r/   error_context)rO   r   rM   rN   r   r   rD      sP    






zJErrorMonitor.monitor_critical_function.<locals>.decorator.<locals>.wrapperrE   rH   rO   rM   rN   rI   r   rJ      s    Bz9ErrorMonitor.monitor_critical_function.<locals>.decoratorrK   )rM   rN   rO   rJ   r   rV   r   monitor_critical_function   s    Ez&ErrorMonitor.monitor_critical_function      @)component_namealert_thresholdalert_on_slow_executionc                    s   t t d fdd}|S )a/  
        Decorator to monitor system health and performance
        
        Args:
            component_name: Name of the system component
            alert_threshold: Execution time threshold in seconds for alerts
            alert_on_slow_execution: Whether to send alerts for slow execution
        r   c                    s    t   fdd}|S )Nc                     s  t   }z| |}t   | }|kr^ r^tdd d|dd dd|jdd	 td
 d|jt  dd |W S  tk
r } zdt   | }t|}t	||jt
|jd tdd d| d|jt
|jdd	  W 5 d }~X Y nX d S )NZPERFORMANCE_WARNINGzSlow execution detected in r#   z.2fzs (threshold: zs)WARNING)rY   r%   	thresholdrM   )Z
alert_typemessageZseverityr)   zSystem component executed: r$   )rY   r%   rM   r&   r'   )rY   r%   rM   r0   ZCOMPONENT_FAILUREzSystem component 'rP   CRITICAL)r3   r   r@   r	   r   r7   r8   r>   r   r   r?   )r!   r"   rA   rB   r%   rC   r/   )r[   rZ   rY   r   r   r   rD      sZ    

zFErrorMonitor.monitor_system_health.<locals>.decorator.<locals>.wrapperrE   rH   r[   rZ   rY   rI   r   rJ      s    Cz5ErrorMonitor.monitor_system_health.<locals>.decoratorrK   )rY   rZ   r[   rJ   r   r`   r   monitor_system_health   s    Fz"ErrorMonitor.monitor_system_healthN)TTT)TT)rX   T)r@   
__module____qualname____doc__staticmethodr   boolrL   rW   floatra   r   r   r   r   r      s0         R  r   Tr   c                 C   s   t jd| dS )zMonitor OpenAI API callsOpenAIrh   r   rL   rh   r   r   r   monitor_openai_apiE  s    rk   c                 C   s   t jd| dS )zMonitor Jira API callsJirarh   rj   rh   r   r   r   monitor_jira_apiI  s    rm   c                 C   s   t jd| dS )zMonitor Azure DevOps API callszAzure DevOpsrh   rj   rh   r   r   r   monitor_azure_apiM  s    rn   rM   c                   s$    fdd}| dkr|S || S dS )z!Monitor critical system functionsc                    s    p| j }t|| S )N)r@   r   rW   )fnamero   r   r   rJ   S  s    
z*monitor_critical_system.<locals>.decoratorNr   )r   rM   rJ   r   ro   r   monitor_critical_systemQ  s    rr   rX   rY   r]   c                    s    fdd}|S )zMonitor system performancec                    s    p| j }tj|dS )N)rZ   )r@   r   ra   )r   rq   rs   r   r   rJ   ^  s    
z-monitor_system_performance.<locals>.decoratorr   )rY   r]   rJ   r   rs   r   monitor_system_performance\  s    rt   )T)T)T)N)NrX   )!rd   rF   loggingr3   	tracebacktypingr   r   r   r   r   r   r9   utils.error_loggerr   r	   utils.email_notifierr
   r   r   	getLoggerr@   r6   r   rf   rk   rm   rn   r   rr   rg   rt   Zerror_monitorr   r   r   r   <module>   s&   
  1