
    ;3hi                        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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mZmZmZmZ d dlZd dlZd dlmZ d	d
l m!Z!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+ d	dl,m-Z- d	dl.m/Z/m0Z0 d	dl1m2Z2m3Z3 d	dl4m5Z5 d	dl6m7Z7m8Z8 d	dl9m:Z: d	dl;m<Z< d	dl=m>Z>m?Z? dZ@er
d dlAZAd	dlBmCZC ee*e3de"dge<f   ZDee<gee?   f   ZE e*dde)i i dddd ej                  d      
      ZG G d deH      ZI G d  d!eH      ZJ eJ       ZK ej                  ddd"       G d# d$             ZMeee*eMf   e3f   ZN G d% de$      ZOy)&    N)deque)suppress)escape)
HTTPStatus)Logger)TYPE_CHECKINGAny	AwaitableCallableDequeOptionalSequenceTupleTypeUnioncast)under_cached_property   )AbstractAccessLoggerAbstractStreamWriter)BaseProtocol)ceil_timeout)HttpProcessingErrorHttpRequestParserHttpVersion10RawRequestMessageStreamWriter)BadHttpMethod)access_loggerserver_logger)EMPTY_PAYLOADStreamReader)tcp_keepalive)HTTPExceptionHTTPInternalServerError)AccessLogger)BaseRequest)ResponseStreamResponse)RequestHandlerRequestPayloadErrorPayloadAccessError)Serverr*   zasyncio.Task[None]UNKNOWN/TFc                       e Zd ZdZy)r+   zPayload parsing error.N__name__
__module____qualname____doc__     T/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/aiohttp/web_protocol.pyr+   r+   S   s     r7   r+   c                       e Zd ZdZy)r,   z-Payload was accessed after response was sent.Nr1   r6   r7   r8   r,   r,   W   s    7r7   r,   )auto_attribsfrozenslotsc                   ,    e Zd ZU eed<   eed<   eed<   y)_ErrInfostatusexcmessageN)r2   r3   r4   int__annotations__BaseExceptionstrr6   r7   r8   r>   r>   ^   s    K	Lr7   r>   c            !           e Zd ZdZdZddeeeej                  dddddd	dd
dddde	j                  dedededee   dedededededededededef  fdZdefdZeded    fd!       Zedeeeeeeeef   eeef   f      fd"       Zedefd#       ZdHd$ee   dd%fd&Zd'e	j:                  dd%f fd(Zd)ee   dd%f fd*Z d+e!dd%fd,Z"dId-Z#d.e$dd%fd/Z%d0edd%fd1Z&dId2Z'dId3Z(d4e)d5e*d6ee   dd%fd7Z+d8e!d9e!dd%fd:Z,d8e!d9e!dd%fd;Z-dId<Z.d4e)d=ee   d>e/e)ge0e*   f   dee*ef   fd?Z1dId@Z2d4e)dAe*d=ee   dee*ef   fdBZ3	 	 	 dJd4e)dCed)ee   dDee   de*f
dEZ4dFe5de/e)ge0e*   f   fdGZ6 xZ7S )Kr*   aj  HTTP protocol implementation.

    RequestHandler handles incoming HTTP request. It reads request line,
    request headers and request payload and calls handle_request() method.
    By default it always returns with 404 response.

    RequestHandler handles errors in incoming request, like bad
    status line, bad headers or incomplete payload. If any error occurs,
    connection gets closed.

    keepalive_timeout -- number of seconds before closing
                         keep-alive connection

    tcp_keepalive -- TCP keep-alive is on, default is on

    debug -- enable debug mode

    logger -- custom logger object

    access_log_class -- custom class for access_logger

    access_log -- custom logging object

    access_log_format -- access log format string

    loop -- Optional event loop

    max_line_size -- Optional maximum header line size

    max_field_size -- Optional maximum header field size

    max_headers -- Optional maximum header size

    timeout_ceil_threshold -- Optional value to specify
                              threshold to ceil() timeout
                              values

    )_request_count
_keepalive_manager_request_handler_request_factory_tcp_keepalive_next_keepalive_close_time_keepalive_handle_keepalive_timeout_lingering_time	_messages_message_tail_handler_waiter_waiter_task_handler_upgrade_payload_parser_request_parser_reading_pausedloggerdebug
access_logr   _close_force_close_current_request_timeout_ceil_threshold_request_in_progress_logging_enabled_cachei.  TFi  i   g      $@i      )keepalive_timeoutr#   rZ   access_log_classr\   access_log_formatr[   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdmanagerr-   loopre   r#   rZ   rf   r\   rg   r[   rh   ri   rj   rk   rl   rm   rn   c          
         t         |   |       d| _        d| _        d | _        || _        |j                  | _        |j                  | _	        || _
        d| _        d | _        || _        t        |      | _        t!               | _        d| _        d | _        d | _        d | _        d| _        d | _        t1        | |||
||t2        |      | _        d| _        	 t        |      | _        || _        |	| _        || _         |r* |||      | _!        | jB                  jD                  | _#        nd | _!        d| _#        d| _$        d| _%        d| _&        i | _'        y # t8        t:        f$ r Y }w xY w)Nr   Fg        r7   )rh   rj   ri   payload_exceptionrm   rd   )(super__init__rG   rH   r_   rI   request_handlerrJ   request_factoryrK   rL   rM   rN   rO   floatrP   r   rQ   rR   rT   rS   rU   rV   rW   r   r+   rX   r`   	TypeError
ValueErrorrZ   r[   r\   r   enabledrb   r]   r^   ra   rc   )selfro   rp   re   r#   rZ   rf   r\   rg   r[   rh   ri   rj   rk   rl   rm   rn   	__class__s                    r8   rt   zRequestHandler.__init__   s   * 	  7;*1;B;R;R;B;R;R+*-';?"3$^4*/' 7;?C;?$(<M')#1+	=
 /0$	+01G+HD( 
$AQ-BD %)$6$6$>$>D!!%D$)D!!$)!&(% :& 		s   E E&%E&returnc                 r    dj                  | j                  j                  | j                  d      S d      S )Nz<{} {}>	connecteddisconnected)formatr|   r2   	transportr{   s    r8   __repr__zRequestHandler.__repr__  s;    NN##>>5K
 	
;I
 	
r7   zssl.SSLContextc                 T    | j                   dS | j                   j                  d      S )zReturn SSLContext if available.N
sslcontextr   get_extra_infor   s    r8   ssl_contextzRequestHandler.ssl_context  s1    
 ~~% 	
 ..|<	
r7   c                 T    | j                   dS | j                   j                  d      S )zReturn peername if available.Npeernamer   r   s    r8   r   zRequestHandler.peername  s1     ~~% 	
 ..z:	
r7   c                     | j                   S N)rO   r   s    r8   re   z RequestHandler.keepalive_timeout  s    &&&r7   timeoutNc                   K   d| _         | j                  | j                  j                          | j                  rX| j                  j                         | _        	 t        |      4 d{    | j                   d{    ddd      d{    	 t        |      4 d{    | j                  -| j                  j!                  t        j                                | j"                  A| j"                  j%                         s't        j&                  | j"                         d{    ddd      d{    | j"                  | j"                  j                          | j)                          y7 7 7 # 1 d{  7  sw Y   xY w# t        j                  t        j                  f$ rE d| _        t        j                  dk\  r't        j                         x}r|j                         r Y ew xY w7 Y7 7 # 1 d{  7  sw Y   xY w# t        j                  t        j                  f$ r> t        j                  dk\  r't        j                         x}r|j                         r Y :w xY ww)zDo worker process exit preparations.

        We need to clean up everything and stop accepting requests.
        It is especially important for keep-alive connections.
        TN      )r^   rN   cancelra   _loopcreate_futurerS   r   asyncioCancelledErrorTimeoutErrorsysversion_infocurrent_task
cancellingr_   _cancelrU   doneshieldforce_close)r{   r   tasks      r8   shutdownzRequestHandler.shutdown   s     !!!-""))+ $$ $(::#;#;#=D 
'0 / /..../ /	#G, = =((4))11'2H2H2JK%%1$:L:L:Q:Q:S!..););<<<= = )%%'=/./ / / /**G,@,@A '+$$$/!(!5!5!777)=
 == = = = &&(<(<= 	  G+$1133T3OO%	s   AI=F +E6,F /E=?E9 E=F E;F H $G=%H (BH*H +H/H :H;H ?7I=6F 9E=;F =FFFF A$G:6I=9G::I==H  HH H
HHH AI:6I=9I::I=r   c                    t         |   |       t        t        j                  |      }| j
                  rt        |       | j                  J | j                  j                  | |       | j                  }t        j                  dk\  r.t        j                  | j                         |d      }|| _        y |j                  | j                               }|| _        y )Nr      Trp   eager_start)rs   connection_mader   r   	TransportrL   r#   rI   r   r   r   Taskstartcreate_taskrU   )r{   r   real_transportrp   r   r|   s        r8   r   zRequestHandler.connection_madeR  s    	*g//;.)}}(((%%dN;zzw&<<

4TJD " ##DJJL1D!r7   r@   c                 h   | j                   y | j                   j                  | |       | j                   j                  }| j                          t        |   |       d | _         d | _        d | _        d | _        | j                  | j                  j                          | j                  (|t        d      }| j                  j                  |       |r&| j                  | j                  j                          d | _        | j                  "| j                  j                          d | _        y y )NzConnection lost)rI   connection_losthandler_cancellationr   rs   rK   rJ   rX   rN   r   r_   ConnectionResetErrorr   rU   rW   feed_eof)r{   r@   r   r|   s      r8   r   zRequestHandler.connection_lostc  s   == %%dC0  $}}AA$ $ $#!!-""))+  ,{*+<=!!))#.D$6$6$B%%'!+  ))+#'D  ,r7   parserc                     | j                   J || _         | j                  r-| j                   j                  | j                         d| _        y y )Nr7   )rW   rR   	feed_data)r{   r   s     r8   
set_parserzRequestHandler.set_parser  sL    ##+++%  **4+=+=>!$D r7   c                      y r   r6   r   s    r8   eof_receivedzRequestHandler.eof_received  s    r7   datac                 
   | j                   s| j                  ry | j                  | j                  s| j                  J 	 | j                  j                  |      \  }}}|xs dD ]7  \  }}| xj                  dz  c_
        | j                  j                  ||f       9 | j                  }|r#|!|j                         s|j                  d        || _        |r|r|| _        y y y | j                  $| j                  r|r| xj                   |z  c_        y |r2| j                  j                  |      \  }	}|	r| j#                          y y y # t        $ r.}t        d||j                        t        fg}d}d}Y d }~d }~ww xY w)Ni  )r?   r@   rA   Fr7   r6   r   )r^   r]   rW   rV   rX   r   r   r>   rA   r!   rG   rQ   appendrT   r   
set_resultrR   close)
r{   r   messagesupgradedtailr@   msgpayloadwaitereofs
             r8   data_receivedzRequestHandler.data_received  sv    '''333+/+?+?+I+I$+O((D !)B 6W##q(#%%sGn56 \\FF.v{{}!!$'$DMD%)" !x !!)dmm$& ,,66t<IC

  3 ' Sc3;;GW !s   E 	F#E==Fvalc                 n    || _         | j                  r"| j                  j                          d| _        yy)zMSet keep-alive connection mode.

        :param bool val: new state.
        N)rH   rN   r   )r{   r   s     r8   
keep_alivezRequestHandler.keep_alive  s3    
 !!""))+%)D" "r7   c                 `    d| _         | j                  r| j                  j                          yy)zClose connection.

        Stop accepting new pipelining messages and close
        connection when handlers done processing messages.
        TN)r]   rT   r   r   s    r8   r   zRequestHandler.close  s'     <<LL! r7   c                     d| _         | j                  r| j                  j                          | j                  "| j                  j	                          d| _        yy)zForcefully close connection.TN)r^   rT   r   r   r   r   s    r8   r   zRequestHandler.force_close  sG     <<LL!>>%NN  "!DN &r7   requestresponsetimec                     | j                   Z| j                   j                  rCt        r|J | j                   j                  ||| j                  j                         |z
         y y y r   )r   rz   r   logr   r   )r{   r   r   r   s       r8   
log_accesszRequestHandler.log_access  s^     )d.@.@.H.H'''""7Hdjjoo6G$6NO /I)r7   argskwc                 V    | j                   r | j                  j                   |i | y y r   )r[   rZ   r{   r   r   s      r8   	log_debugzRequestHandler.log_debug  s'    ::DKKt*r* r7   c                 <     | j                   j                  |i | y r   )rZ   	exceptionr   s      r8   log_exceptionzRequestHandler.log_exception  s    t*r*r7   c                 R   d | _         | j                  s| j                  sy | j                  }|j	                         }| j
                  }||k  r"|j                  || j                        | _         y | j                  r,| j                  j                         s| j                          y y y r   )rN   r^   rH   r   r   rM   call_at_process_keepaliverT   r   r   )r{   rp   now
close_times       r8   r   z!RequestHandler._process_keepalive  s    !%DOOzziik44
%)\\*d>U>U%VD" << 1 1 3 !4<r7   
start_timeru   c                   K   d| _         	 	 || _         ||       d {   }d | _        	 t        |dd      rt        j                  dt
               | j                  |||       d {   \  }}d| _         | j                  | j                  j                  d        ||fS 7 # d | _        w xY w7 G# t        $ r+}|}| j                  |||       d {  7  \  }}Y d }~qd }~wt        j                  $ r  t        j                  $ rN}| j                  d|       | j                  |d      }| j                  |||       d {  7  \  }}Y d }~d }~wt        $ r=}| j                  |d|      }| j                  |||       d {  7  \  }}Y d }~'d }~ww xY w# d| _         | j                  | j                  j                  d        w w xY ww)	NT__http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception insteadzRequest handler timed out.exc_infoi    )ra   r_   getattrwarningswarnDeprecationWarningfinish_responser$   r   r   r   r   handle_error	ExceptionrS   r   )r{   r   r   ru   respresetr@   s          r8   _handle_requestzRequestHandler._handle_request  s     %)! 	6-(/%,W55(,% t1599 '	 !% 4 4WdJ OOKD%(-D%##/$$//5U{? 6(,%. P-  	PD $ 4 4WdJ OOOKD%%% 	## 	PNN7#NF$$Wc2D $ 4 4WdJ OOOKD% 	P$$Wc37D $ 4 4WdJ OOOKD%	P ).D%##/$$//5 0s   GB$ B"B$ B2 =F (B0)F 02G"B$ $	B--B2 0F 2	F;C!CC!F !)F
;EEEF F)FF	FF FF 1GGc           	      @  K   | j                   }| j                  }|J | j                  }d}| j                  J | j                  J | j
                  s{| j                  s1	 |j                         | _        | j                   d{    d| _        | j                  j                         \  }}| j                  r|j                         nd}|xj                  dz  c_        t        | |      }t        |t              r| j!                  |      }	t"        }n| j                  }	| j                  ||| || j$                  xs t'        j(                  |            }
	 | j+                  |
||	      }t,        j.                  dk\  rt'        j0                  ||d      }n|j3                  |      }	 | d{   \  }}~|r<| j7                  d       	 d|
_        | j:                  || j7                  d       nt=        |j>                        | _         |jC                         s| jD                  }| j
                  s|r| j7                  d	|       |j                         }||z   }	 |jC                         sj||k  retG        ||z
        4 d{    |jI                          d{    ddd      d{    |j                         }|jC                         s||k  re|jC                         s-| j
                  s!| j7                  d       | jQ                          |jS                  tT               d|
_        | j:                  || j7                  d       	 | j@                  r`| j^                  sT| j
                  sH|j                         |z   }|| _0        | jb                  #|je                  || jf                        | _1        nn| j
                  s{| j
                  s/d| _        | j:                  | j:                  jQ                          yyy7 # d| _        w xY w7 l# t4        $ r< | j7                  d       Y d|
_        | j:                  }|| j7                  d       w xY w7 7 7 # 1 d{  7  sw Y   xY w# t&        jJ                  t&        jL                  f$ r> t,        j.                  d
k\  r't'        j(                         x}r|jO                         r Y 	w xY w# t&        jJ                  $ r# | j7                  d       | jW                           tX        $ r.}| j[                  d|       | jW                          Y d}~!d}~wt\        $ r | jW                           w xY w# d|
_        | j:                  || j7                  d       w w w xY ww)a_  Process incoming request.

        It reads request line, request headers and request payload, then
        calls handle_request() method. Subclass has to override
        handle_request(). start() handles various exceptions in request
        or response handling. Connection is being closed always unless
        keep_alive(True) specified.
        Nr   r   Tr   z&Ignored premature client disconnectionz'Ignored premature client disconnection.z(Ignored premature client disconnection 2z'Start lingering close timer for %s sec.r   zUncompleted request.zUnhandled exceptionr   )4r   rI   rO   rK   rJ   r^   rQ   r   rT   popleftrb   r   requests_countr   
isinstancer>   _make_error_handlerERRORrU   r   r   r   r   r   r   r   ConnectionErrorr   _taskr   boolr   rH   is_eofrP   r   readanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rD   r]   rM   rN   r   r   )r{   rp   ro   re   r   rA   r   r   writerru   r   coror   r   rk   r   end_ttr@   r   s                       r8   r   zRequestHandler.start  s     zz--""" 33$$000$$000##>>(#'#5#5#7DL,,&&#'DL#~~557GW $(#8#8DIIKdE""a'"!$-F'8,"&":":7"C"&"7"7
 ++""@g&:&:4&@GCN++GUOL##w."<<4TJD++D1D(,*KD% NN#MN` !%>>)d.>NN#LM_ #'t"7 ~~'%)%9%9N,,E~ #iik #n 4&&-nn&63;+7+D !< !<*1//*;$;$;!< !< '+iik	 '.nn&63; #>>+D4E4E'=>

%%&;< !%>>)d.>NN#LMt{{4;L;L!YY[+<<
2</))1-1\\"D$;$;.D* a ##f   !%D~~)$$& * !] '#'DLF #-& NN#KLl !%>>)d.>NN#LMu4!<$;!< !< !< !< !( 6 68L8LM & # 0 0G ;*1*>*>*@%@Q%@$%LLN %& )) GH  " #""#83"G  ""    " !%>>)d.>NN#LM /?)sD  A V#$P PP CVAS* +P 0P1P 8S* *V7A+S* #'R 
Q'R Q0"Q*#Q0'R 2Q-3)R AS* /B V<VP 	PVP Q$9S* :VVV#Q$$S* 'R *Q0-R 0R6Q97R>R AS'#S* &S''S* *=U.'#U
U1 U..U1 1*VVr   c                   K   |j                          | j                  Z| j                  j                  d       d| _        | j                  r,| j                  j                  | j                         d| _        	 |j                  }	  ||       d{    |j!                          d{    | j%                  |||       |dfS # t        $ r || j                  d       n | j                  dj                  |             t               }t        |j                  |j                  |j                  |j                        }|j                  }Y w xY w7 7 # t"        $ r | j%                  |||       |dfcY S w xY ww)a   Prepare the response and write_eof, then log access.

        This has to
        be called within the context of any exception so the access logger
        can get exception information. Returns True if the client disconnects
        prematurely.
        NFr7   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r})r?   reasontextheadersT)_finishrX   set_upgradedrV   rR   r   prepareAttributeErrorr   r   r%   r(   r?   r   r  r  	write_eofr   r   )r{   r   r   r   prepare_methr@   s         r8   r   zRequestHandler.finish_response  s[     	+  --e4!DM!!$$..t/A/AB%("	(<<L	w'''.."""
 	z2U{+  	(|""#PQ""%vd| *+Czz#**388S[[D  <<L	( (" 	OOGT:6:	sm   A7F :C E EE *E+E /F B
EF EF E E  E=:F <E==F r?   rA   c                 $   | j                   dk(  r9t        |t              r)| j                  j	                  d|j
                  |       n| j                  d|j
                  |       |j                  j                  dkD  rt        d      d}|t        j                  k(  rdj                  t        j                        }t        j                  j                  }d}| j                  r,t        t              5  t!        j"                         }ddd       d	|j$                  j'                  d
d      v r)|rt)        |      }d| d}dj                  ||      }d	}n|r|}|dz   |z   }t+        |||      }	|	j-                          |	S # 1 sw Y   |xY w)zHandle errors.

        Returns HTTP response with specific status code. Logs additional
        information. It always closes current connection.
        r   zError handling request from %sr   r   zMResponse is sent already, cannot send another response with the error messagez
text/plainz{0.value} {0.phrase}Nz	text/htmlAccept z<h2>Traceback:</h2>
<pre>z</pre>zV<html><head><title>{title}</title></head><body>
<h1>{title}</h1>
{msg}
</body></html>
)titler   z

)r?   r  content_type)rG   r   r   rZ   r[   remoter   r   output_sizer   r   INTERNAL_SERVER_ERRORr   descriptionr   r   	traceback
format_excr  gethtml_escaper(   r   )
r{   r   r?   r@   rA   ctr  r   tbr   s
             r8   r   zRequestHandler.handle_error  s    !#
3(F
 KK0'..3   0'..3  
 >>%%)!) 
 Z555*11*2R2RSE22>>CBzzi( 0"--/B0 goo11(B??$RB6rd&AC0 &u#&.  !C&.3.vG"E-0 0s   6FFerr_infoc                 0     dt         dt        f fd}|S )Nr   r}   c                 p   K   j                  | j                  j                  j                        S wr   )r   r?   r@   rA   )r   r  r{   s    r8   handlerz3RequestHandler._make_error_handler.<locals>.handler  s1     $$(,,8H8H s   36)r'   r)   )r{   r  r  s   `` r8   r   z"RequestHandler._make_error_handler  s    	; 	> 	
 r7   )g      .@)r}   N)r   NN)8r2   r3   r4   r5   	__slots__r    r&   r   
LOG_FORMATr   AbstractEventLooprw   r   r   r   r   rE   rB   rt   r   r   r   r   r   r   r   propertyre   r   BaseTransportr   rD   r   r	   r   r   bytesr   r   r   r   r'   r)   r   r   r   r   r   r
   r   r   r   r   r>   r   __classcell__)r|   s   @r8   r*   r*   h   s   %NIN $("&7C*!-!8!8! " $! $()'O)O) ''	O) !O) O) O) 34O) O) O) O) O) O) O)  !O)" #O)$ %O)& !&'O)b
# 
 
X&67 
 
 
	%U3S##56c3hGH	I
 
 '5 ' '0huo 0 0d")>)> "4 ""(8M#: (t (@% % %%% %D %N*d *t *""P"P.<PDLUOP	P+s +# +$ ++3 +c +d +")) UO) ";->1J"JK	)
 
~t#	$)VG'R("(*8(FNuo(	~t#	$(Z '+!%<< < m$	<
 #< 
<| 	;->!::	;r7   )Pr   asyncio.streamsr   r  r   collectionsr   
contextlibr   htmlr   r  httpr   loggingr   typingr   r	   r
   r   r   r   r   r   r   r   r   attryarl	propcacher   abcr   r   base_protocolr   helpersr   r   r   r   r   r   http_exceptionsr   r   r   r    streamsr!   r"   tcp_helpersr#   web_exceptionsr$   r%   web_logr&   web_requestr'   web_responser(   r)   __all__ssl
web_serverr-   _RequestFactory_RequestHandlerURLr   r   r+   r,   r   sr>   _MsgTyper*   r6   r7   r8   <module>r?     sf     
     &        + ; ' !  + - 0 & B ! $ 2
I"  	 K=)N*CCD		DHHSM	!) !8 8 +,  T$d3  4 ((23\ABp
\ p
r7   