
    +j                     $   d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlZ ej	        e
          Zd ZdedefdZddd	ed
edefdZdedededefdZdedefdZ	 	 	 	 	 	 	 d7dededededz  dedz  dededz  dedz  dededz  fdZe
dk    r|e                    ej                    eed          s G d d          Z e            Z edd d!d"d#id$d%id&d'd(i)            ed*d+d,d-d.d/id0d12            ed3d d4d&d56           dS dS )8    N)Anyc                      t          j                    } t          j                            | d          }	 t          j        |d           nB# t          $ r5}t                              d|t          |                     | cY d}~S d}~ww xY w|S )zZEnsures the API log directory exists within ComfyUI's temp directory and returns its path.api_logsTexist_okz'Error creating API log directory %s: %sN)
folder_pathsget_temp_directoryospathjoinmakedirs	Exceptionloggererrorstr)base_temp_dirlog_dires      C/home/wildlama/comfy/ComfyUI/comfy_api_nodes/util/request_logger.pyget_log_directoryr      s     355Mgll=*55G
Gd+++++   >QPPP Ns   A 
B*B BBnamereturnc                 l    | sdS t          j        dd|           }|                    d          }|sd}|S )Nlogz[^A-Za-z0-9._-]+_z ._)resubstrip)r   	sanitizeds     r   _sanitize_filename_componentr       sG     u*C66I&&I 	    
   )lengthpartsr#   c                     t          j        d                    |                              d                                                    d |          S )N|utf-8)hashlibsha1r   encode	hexdigest)r#   r$   s     r   _short_hashr,   %   s?    <%0099::DDFFwwOOr!   r   operation_idrequest_urlc                    t           j                                                             d          }t          |          }t	          |pd|pd          }d}| d}d| d}|sd}t          d|t          |           z
  dz
            }	t          d	|	t          |          z
  t          |          z
            }
t          |          |
k    r|d
|
                             d          }t          j	        
                    | | | |           S )zgBuild log filepath. We keep it well under common path length limits aiming for <= 240 characters total.z%Y%m%d_%H%M%S_%f    r   z.logop<         Nz ._-)datetimenowstrftimer    r,   maxlenrstripr
   r   r   )r   r-   r.   	timestampslughmax_total_pathprefixsuffixmax_filename_lenmax_slug_lens              r   _build_log_filepathrD   )   s   !%%''001CDDI'55DL&B(9r::A N___F[[[F 2~G<q@AAq*S[[83v;;FGGL
4yy<M\M"))&117<<F!:D!:&!:!:;;;r!   datac                 b   t          | t                    r9	 |                     d          S # t          $ r dt	          |            dcY S w xY wt          | t
          t          f          r7	 t          j        | dd          S # t          $ r t          |           cY S w xY wt          |           S )z5Helper to format data (dict, str, bytes) for logging.r'   z[Binary data of length z bytes]   F)indentensure_ascii)
isinstancebytesdecodeUnicodeDecodeErrorr:   dictlistjsondumps	TypeErrorr   )rE   s    r   _format_data_for_loggingrS   =   s    $ 		@;;w'''! 	@ 	@ 	@?SYY??????	@	D4,	'	' 	:d15AAAA 	 	 	t99	t99s!   , AA,B BBrequest_methodrequest_headersrequest_paramsrequest_dataresponse_status_coderesponse_headersresponse_contenterror_messagec
                 `   	 t                      }
t          |
| |          }g }|                    dt          j                                                                                    |                    d|             |                    d           |                    d|            |                    d|            |r%|                    dt          |                      |r%|                    dt          |                      |%|                    d	t          |                      |                    d
           ||                    d|            |r%|                    dt          |                      |%|                    dt          |                      |	r|                    d|	            	 t          |dd          5 }|                    d	                    |                     ddd           n# 1 swxY w Y   t                              d|           dS # t          $ r4}t                              d|t          |                     Y d}~dS d}~ww xY w# t          $ r }t          j        d|           Y d}~dS d}~ww xY w)z
    Logs API request and response details to a file in the temp/api_logs directory.
    Filenames are sanitized and length-limited for cross-platform safety.
    If we still fail to write, we fall back to appending into api.log.
    zTimestamp: zOperation ID: zE------------------------------ REQUEST ------------------------------zMethod: zURL: z	Headers:
zParams:
NzData/Body:
zG
------------------------------ RESPONSE ------------------------------zStatus Code: z	Content:
zError:
wr'   )encoding
zAPI log saved to: %szError writing API log to %s: %sz'[DEBUG] log_request_response failed: %s)r   rD   appendr6   r7   	isoformatrS   openwriter   r   debugr   r   r   logging)r-   rT   r.   rU   rV   rW   rX   rY   rZ   r[   r   filepathlog_contentfr   _log_es                   r   log_request_responserj   L   sR   ""I#%%&wkJJ!#N):)>)>)@)@)J)J)L)LNNOOO:L::;;;<===6n667770;00111 	YW,D_,U,UWWXXX 	WU+CN+S+SUUVVV#V.F|.T.TVVWWWDEEE+E/CEEFFF 	ZX,DEU,V,VXXYYY'X,DEU,V,VXXYYY 	;9-99:::	Nhg666 0!		+..///0 0 0 0 0 0 0 0 0 0 0 0 0 0 0LL/::::: 	N 	N 	NLL:Hc!ffMMMMMMMMM	N I I I?HHHHHHHHHIs`   GJ I %)HI HI !H"I 
J )I;5J ;J  J 
J-J((J-__main__r	   c                       e Zd Zd ZdS )MockFolderPathsc                     t           j                            t           j                            t                    d          }t          j        |d           |S )Ntemp_test_logsTr   )r
   r   r   dirname__file__r   )selfps     r   r	   z"MockFolderPaths.get_temp_directory   s@    GLL!:!:<LMMA----r!   N)__name__
__module____qualname__r	    r!   r   rm   rm      s#            r!   rm   test_operation_getGETzhttps://api.example.com/testAuthorizationzBearer testtokenparam1value1   messagezSuccess!)r-   rT   r.   rU   rV   rX   rZ   test_operation_post_errorPOSTzhttps://api.example.com/submitvaluenum{   )keynestedzConnection timed out)r-   rT   r.   rW   r[   test_binary_responsez!https://api.example.com/image.pngs   PNG

   IHDR...)r-   rT   r.   rX   rZ   )NNNNNNN)r6   r(   rP   re   r
   r   typingr   r   	getLoggerrt   r   r   r   r    intr,   rD   rS   rN   rj   setLevelDEBUGhasattrrm   rw   r!   r   <module>r      s       				 				          		8	$	$
 
 
s s     ,. P P P PS P# P P P P< <C <c <c < < < <(3 3    & $("&'+$(  $3I 3I3I3I 3I D[	3I
 4K3I 3I *3I Tk3I 3I :3I 3I 3I 3Il z
OOGM"""7<!566 )	 	 	 	 	 	 	 	 '(()2(*<= (+ #Z0    04$==,    +7 B     ; r!   