
    Ngc                        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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-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= dZ>erddl?m@Z@ ee(e1de dge:f         ZAee:gee=         f         ZB e(dde'i i dddd ejC        d          
  
        ZD G d deE          ZF G d d eE          ZG eG            ZH ejI        ddd!           G d" d#                      ZJeee(eJf         e1f         ZK G d$ de"          ZLdS )%    N)deque)suppress)escape)
HTTPStatus)Logger)TYPE_CHECKINGAny	AwaitableCallableDequeOptionalSequenceTupleTypeUnioncast   )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dS )r*   zPayload parsing error.N__name__
__module____qualname____doc__     P/var/www/html/ai-engine/env/lib/python3.11/site-packages/aiohttp/web_protocol.pyr*   r*   P   s            r6   r*   c                       e Zd ZdZdS )r+   z-Payload was accessed after response was sent.Nr0   r5   r6   r7   r+   r+   T   s        7777r6   r+   )auto_attribsfrozenslotsc                   .    e Zd ZU eed<   eed<   eed<   dS )_ErrInfostatusexcmessageN)r1   r2   r3   int__annotations__BaseExceptionstrr5   r6   r7   r=   r=   [   s.         KKK	LLLLLr6   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fd             ZdGd"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dHd+Zd,edd#fd-Z d.edd#fd/Z!dHd0Z"dHd1Z#d2e$d3e%d4edd#fd5Z&d6ed7edd#fd8Z'd6ed7edd#fd9Z(dHd:Z)d2e$d;ed<e*e$ge+e%         f         de,e%ef         fd=Z-dHd>Z.d2e$d?e%d;ede,e%ef         fd@Z/	 	 	 dId2e$dBed'ee         dCee         de%f
dDZ0dEe1de*e$ge+e%         f         fdFZ2 xZ3S )Jr)   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_progressi.  TFi  i   g      $@i      )keepalive_timeoutr"   rY   access_log_classr[   access_log_formatrZ   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdmanagerr,   looprb   r"   rY   rc   r[   rd   rZ   re   rf   rg   rh   ri   rj   rk   c          
         t                                          |           d| _        d| _        d | _        || _        |j        | _        |j        | _	        || _
        d| _        d | _        || _        t          |          | _        t!                      | _        d| _        d | _        d | _        d | _        d| _        d | _        t1          | |||
||t2          |          | _        d| _        	 t          |          | _        n# t8          t:          f$ r Y nw xY w|| _        |	| _        || _         |r |||          | _!        nd | _!        d| _"        d| _#        d| _$        d S )Nr   Fg        r6   )re   rg   rf   payload_exceptionrj   ra   )%super__init__rF   rG   r^   rH   request_handlerrI   request_factoryrJ   rK   rL   rM   rN   floatrO   r   rP   rQ   rS   rR   rT   rU   rV   r   r*   rW   r_   	TypeError
ValueErrorrY   rZ   r[   r   r\   r]   r`   )selfrl   rm   rb   r"   rY   rc   r[   rd   rZ   re   rf   rg   rh   ri   rj   rk   	__class__s                    r7   rq   zRequestHandler.__init__   s   * 	  7;*1;B;R;B;R+*-';?"3$^44*/'' 7;?C;?$(<M')#1+	=
 	=
 	=
 /0$	+01G+H+HD((:& 	 	 	D	 
$ 	&AQAQ-B BD "&D!$)!!!s   -D DDreturnc                 T    d                     | j        j        | j        dnd          S )Nz<{} {}>	connecteddisconnected)formatrx   r1   	transportrw   s    r7   __repr__zRequestHandler.__repr__   s0    N#>5KK>
 
 	
r6   c                     | j         S N)rN   r   s    r7   rb   z RequestHandler.keepalive_timeout   s    &&r6         .@timeoutNc                 l  K   d| _         | j        | j                                         | j        r| j                                        | _        	 t          |          4 d{V  | j         d{V  ddd          d{V  n# 1 d{V swxY w Y   nb# t          j	        t          j
        f$ rD d| _        t          j        dk    r*t          j                    x}r|                                r Y nw xY w	 t          |          4 d{V  | j        +| j                            t          j	                               | j        8| j                                        st          j        | j                   d{V  ddd          d{V  n# 1 d{V swxY w Y   n[# t          j	        t          j
        f$ r= t          j        dk    r*t          j                    x}r|                                r Y nw xY w| j        | j                                         |                                  dS )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]   rM   cancelr`   _loopcreate_futurerR   r   asyncioCancelledErrorTimeoutErrorsysversion_infocurrent_task
cancellingr^   _cancelrT   doneshieldforce_close)rw   r   tasks      r7   shutdownzRequestHandler.shutdown  sg      !!-"))+++ $ 	 $(:#;#;#=#=D 
'00 / / / / / / / /......../ / / / / / / / / / / / / / / / / / / / / / / / / / /*G,@A   '+$$//!(!5!7!77 0)) 0 	#G,, = = = = = = = =(4)11'2H2J2JKKK%1$:L:Q:Q:S:S1!.);<<<<<<<<<= = = = = = = = = = = = = = = = = = = = = = = = = = = &(<= 	 	 	 G++$1333T ,OO%% , 	 )%%'''so   B %B3B 
BB BB AC65C6:F% A2FF% 
FF%  F!F% %AG=<G=r~   c                    t                                          |           t          t          j        |          }| j        rt          |           | j        J | j                            | |           | j        }t          j
        dk    r*t          j        |                                 |d          }n'|                    |                                           }|| _        d S )Nr      Trm   eager_start)rp   connection_mader   r   	TransportrK   r"   rH   r   r   r   Taskstartcreate_taskrT   )rw   r~   real_transportrm   r   rx   s        r7   r   zRequestHandler.connection_made6  s    	***g/;; 	*.)))}(((%%dN;;;zw&&<

4TJJJDD##DJJLL11D!r6   r?   c                 R   | j         d S | j                             | |           | j         j        }|                                  t	                                          |           d | _         d | _        d | _        d | _        | j        | j        	                                 | j
        +|t          d          }| j
                            |           |r | j        | j        	                                 d | _        | j        "| j                                         d | _        d S d S )NzConnection lost)rH   connection_losthandler_cancellationr   rp   rJ   rI   rW   rM   r   r^   ConnectionResetErrorr   rT   rV   feed_eof)rw   r?   r   rx   s      r7   r   zRequestHandler.connection_lostG  s0   = F%%dC000  $}A$$$ $ $#!-"))+++ ,{*+<==!))#... 	(D$6$B%%'''!+ ))+++#'D    ,+r6   parserc                     | j         J || _         | j        r(| j                             | j                   d| _        d S d S )Nr6   )rV   rQ   	feed_data)rw   r   s     r7   
set_parserzRequestHandler.set_parserg  sV    #+++% 	% **4+=>>>!$D	% 	%r6   c                     d S r   r5   r   s    r7   eof_receivedzRequestHandler.eof_receivedq  s    r6   datac                    | j         s| j        rd S | j        | j        s| j        J 	 | j                            |          \  }}}n:# t          $ r-}t          d||j                  t          fg}d}d}Y d }~nd }~ww xY w|pdD ]1\  }}| xj
        dz  c_
        | j                            ||f           2| j        }|r+|)|                                s|                    d            || _        |r|r|| _        d S d S d S | j        | j        r|r| xj        |z  c_        d S |r5| j                            |          \  }	}|	r|                                  d S d S d S )Ni  )r>   r?   r@   Fr6   r5   r   )r]   r\   rV   rU   rW   r   r   r=   r@   r    rF   rP   appendrS   r   
set_resultrQ   close)
rw   r   messagesupgradedtailr?   msgpayloadwaitereofs
             r7   data_receivedzRequestHandler.data_receivedt  s    	 	F '''333+/+?+I+I$+O+O((DD&   Sc3;GGGW ! !)B 6 6W##q(##%%sGn5555\F (F.v{{}}.!!$'''$DM *D *%)"""* * * * !)dm))$&  	,66t<<IC 

	 	 s   A 
A?#A::A?valc                 f    || _         | j        r"| j                                         d| _        dS dS )zMSet keep-alive connection mode.

        :param bool val: new state.
        N)rG   rM   r   )rw   r   s     r7   
keep_alivezRequestHandler.keep_alive  sC    
 ! 	*"))+++%)D"""	* 	*r6   c                 X    d| _         | j        r| j                                         dS dS )zClose connection.

        Stop accepting new pipelining messages and close
        connection when handlers done processing messages.
        TN)r\   rS   r   r   s    r7   r   zRequestHandler.close  s9     < 	"L!!!!!	" 	"r6   c                     d| _         | j        r| j                                         | j        "| j                                         d| _        dS dS )zForcefully close connection.TN)r]   rS   r   r~   r   r   s    r7   r   zRequestHandler.force_close  sW     < 	"L!!!>%N  """!DNNN &%r6   requestresponsetimec                     | j         D| j         j        r:| j                             ||| j                                        |z
             d S d S d S r   )r   enabledlogr   r   )rw   r   r   r   s       r7   
log_accesszRequestHandler.log_access  sX     )d.@.H)""7Hdjoo6G6G$6NOOOOO *)))r6   argskwc                 <    | j         r | j        j         |i | d S d S r   )rZ   rY   rw   r   r   s      r7   	log_debugzRequestHandler.log_debug  s6    : 	+DKt*r*****	+ 	+r6   c                 *     | j         j        |i | d S r   )rY   	exceptionr   s      r7   log_exceptionzRequestHandler.log_exception  s"    t*r*****r6   c                 8   d | _         | j        s| j        sd S | j        }|                                }| j        }||k    r"|                    || j                  | _         d S | j        r/| j        	                                s| 
                                 d S d S d S r   )rM   r]   rG   r   r   rL   call_at_process_keepaliverS   r   r   )rw   rm   now
close_times       r7   r   z!RequestHandler._process_keepalive  s    !% 	DO 	Fziikk4
*%)\\*d>U%V%VD"F < 	 1 1 3 3 		 	 	 	r6   
start_timerr   c                   K   d| _         	 	 || _         ||           d {V }d | _        n# d | _        w xY w	 t          |dd          rt          j        dt
                     |                     |||           d {V \  }}n# t          $ r,}|}|                     |||           d {V \  }}Y d }~nd }~wt          j	        $ r  t          j
        $ rW}|                     d|           |                     |d          }|                     |||           d {V \  }}Y d }~nQd }~wt          $ rA}|                     |d|          }|                     |||           d {V \  }}Y d }~nd }~ww xY wd| _         | j        | j                            d            n.# d| _         | j        | j                            d            w w xY w||fS )	NT__http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception insteadzRequest handler timed out.exc_infoi    )r`   r^   getattrwarningswarnDeprecationWarningfinish_responser#   r   r   r   r   handle_error	ExceptionrR   r   )rw   r   r   rr   respresetr?   s          r7   _handle_requestzRequestHandler._handle_request  s      %)! 	6-(/%,_W55555555(,%%%,,,,% t1599 9 '	   !% 4 4WdJ O OOOOOOOKD%%-  	P 	P 	PD $ 4 4WdJ O OOOOOOOKD%%%%%%% 	 	 	# 	P 	P 	PNN7#NFFF$$Wc22D $ 4 4WdJ O OOOOOOOKD%%%%%% 	P 	P 	P$$Wc377D $ 4 4WdJ O OOOOOOOKD%%%%%%	P ).D%#/$//555 ).D%#/$//5555 0 U{sa   , B 	5B AF# 
E7"B61F# 6!E7AD)$F# )E767E2-F# 2E77F# #+Gc                   K   | j         }t          j        |          }|J | j        }|J | j        }d}| j        J | j        J | j        s| j        s;	 |	                                | _
        | j
         d{V  d| _
        n# d| _
        w xY w| j                                        \  }}|                                }|xj        dz  c_        t          | |          }	t          |t                     r|                     |          }
t$          }n| j        }
|                     ||| |	|          }	 |                     |||
          }t(          j        dk    rt          j        ||d          }n|                    |          }	 | d{V \  }}n# t0          $ r |                     d           Y | j        ||                     d           nB| j        s[| j        rR| j        sK|G|                                }||z   }|| _        | j         |                    || j                   | _        nnnw xY w~|r|                     d           	 | j        ||                     d           n| j        s[| j        rR| j        sK|G|                                }||z   }|| _        | j         |                    || j                   | _        nAn?n=tC          |j"                  | _        |#                                s| j$        }| j        s-|r*|                     d	|           |                                }||z   }	 |#                                s||k     rtK          ||z
            4 d{V  |&                                 d{V  ddd          d{V  n# 1 d{V swxY w Y   |                                }|#                                s||k     n[# t          j'        t          j(        f$ r= t(          j        d
k    r*t          j                    x}r|)                                r Y nw xY w|#                                s0| j        s)|                     d           | *                                 |+                    tX                     nf# t          j'        $ r |                     d            tZ          $ r5}| .                    d|           | /                                 Y d}~nd}~ww xY w| j        ||                     d           n| j        sY| j        rQ| j        sJ|G|                                }||z   }|| _        | j         |                    || j                   | _        nnn# | j        ||                     d           nb| j        s[| j        rQ| j        sJ|G|                                }||z   }|| _        | j         |                    || j                   | _        n Y nw xY w| j        | j        s)d| _0        | j        | j        *                                 dS dS dS )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   )1r   r   r   rH   rN   rJ   rI   r]   rP   r   rS   popleftr   requests_countr   
isinstancer=   _make_error_handlerERRORr   r   r   r   r   ConnectionErrorr   r~   rG   r\   rL   rM   r   r   boolr   is_eofrO   r   readanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rT   )rw   rm   handlerrl   rb   r   r@   r   r   writerrr   r   coror   r   r   r   rh   end_ttr?   s                        r7   r   zRequestHandler.start  s      z&t,,"""-""" 3$000$000# b	> ((#'#5#5#7#7DL,&&&&&&&#'DLL4DL''''#~5577GWIIKKE""a'""!$--F'8,, 8"&":":7"C"C"&"7++GWdFGTTGK++GUOLL#w.."<4TJJJDD++D11D(,******KD%%&   NN#KLLLd >)d.>NN#LMMMM*  t{ ,8"&))++C),/@)@J>HD;#5=9=$.0G:" :" 6 m
  NN#MNNNX >)d.>NN#LMMMM*  t{ ,8"&))++C),/@)@J>HD;#5=9=$.0G:" :" 6 W #'t"7"7 ~~'' %%)%9N, & &E~   #iikk #n 4&&-nn&6&6 23;;+7+D+D !< !< !< !< !< !< !< !<*1//*;*;$;$;$;$;$;$;$;!< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< !< '+iikk	 '.nn&6&6 23;;
 !( 68LM & & & # 0G ; ;*1*>*@*@%@Q !<$%LLNN !< !&& #>>++ %D4E %'=>>>

%%&;<<<<)   GHHH # # #""#83"GGG  """"""""# >)d.>NN#LMMMM*  t{ ,8"&))++C),/@)@J>HD;#5=9=$.0G:" :" 6  >)d.>NN#LMMMM*  t{ ,8"&))++C),/@)@J>HD;#5=9=$.0G:" :" 6 E # b	J   	'!%D~)$$&&&&&	' 	'))s   &B 	B5AR$ 
F R$ H;5R$ :H;;R$ A/R$ 2O* =N*O* *
N44O* 7N481O* )R$ *AQ?R$ QA!R$ #V
 $.T+T=V
 TV
 
B XXr   c                   K   |                                  | j        N| j                            d           d| _        | j        r&| j                            | j                   d| _        	 |j        }n# t          $ r ||                     d           n(|                     d	                    |                     t                      }t          |j        |j        |j        |j                  }|j        }Y nw xY w	  ||           d{V  |                                 d{V  n+# t"          $ r |                     |||           |dfcY S w xY w|                     |||           |dfS )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.
        NFr6   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r})r>   reasontextheadersT)_finishrW   set_upgradedrU   rQ   r   prepareAttributeErrorr   r}   r$   r'   r>   r   r   r   	write_eofr   r   )rw   r   r   r   prepare_methr?   s         r7   r   zRequestHandler.finish_response~  s      	+ --e444!DM! )$..t/ABBB%("	(<LL 	( 	( 	(|""#PQQQQ""%vd||   *++Cz#*38S[  D  <LLL	(	,w'''''''''.."""""""""" 	 	 	OOGT:666:	 	z222U{s%   -A5 5BC>=C>+D. .%EEr   r>   r@   c                     | j         dk    r2t          |t                    r| j                            d|           n|                     d|           |j        j        dk    rt          d          d}|t          j
        k    rd                    t          j
                  }t          j
        j        }d}| j        r?t          t                    5  t          j                    }ddd           n# 1 swxY w Y   d	|j                            d
d          v r1|rt'          |          }d| d}d                    ||          }d	}n|r|}|dz   |z   }t)          |||          }	|	                                 |	S )zHandle errors.

        Returns HTTP response with specific status code. Logs additional
        information. It always closes current connection.
        r   zError handling requestr   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)rF   r   r   rY   rZ   r   r   output_sizer   r   INTERNAL_SERVER_ERRORr}   descriptionr   r   	traceback
format_excr   gethtml_escaper'   r   )
rw   r   r>   r?   r@   ctr  r   tbr   s
             r7   r   zRequestHandler.handle_error  s    !##
3(F(F#
 K6EEEE7#FFF >%))!)  
 Z555*11*2RSSE2>CBz 0i(( 0 0"-//B0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 go11(B???? B$RBArAAAC0 &u#&..  ! C&.3.vG"EEEs   C33C7:C7err_infoc                 4     dt           dt          f fd}|S )Nr   ry   c                 V   K                        | j        j        j                  S r   )r   r>   r?   r@   )r   r  rw   s    r7   r   z3RequestHandler._make_error_handler.<locals>.handler  s/      $$(,8H  r6   )r&   r(   )rw   r  r   s   `` r7   r   z"RequestHandler._make_error_handler  s<    	; 	> 	 	 	 	 	 	 	
 r6   )r   )ry   N)r   NN)4r1   r2   r3   r4   	__slots__r   r%   r   
LOG_FORMATr   AbstractEventLooprt   r   r   r   r   rD   rA   rq   r   propertyrb   r   r   BaseTransportr   rC   r   r	   r   r   bytesr   r   r   r   r&   r(   r   r   r   r   r   r
   r   r   r   r   r   r=   r   __classcell__)rx   s   @r7   r)   r)   e   s       % %NIJ $("&7C*!-!8! " $! $()'L* L* L*L* '	L* !L* L* L* 34L* L* L* L* L* L* L*  !L*" #L*$ %L*& !&'L* L* L* L* L* L*\
# 
 
 
 
 '5 ' ' ' X'0 0huo 0 0 0 0 0d")> "4 " " " " " ""(8M#: (t ( ( ( ( ( (@% % % % % %   %% %D % % % %N*d *t * * * *" " " "" " " "P"P.<PDIP	P P P P+s +# +$ + + + ++3 +c +d + + + +   ")) ) ";->1J"JK	)
 
~t#	$) ) ) )V{' {' {' {'z("(*8(FK(	~t#	$( ( ( (Z '+!%8 88 8 m$	8
 #8 
8 8 8 8t 	;->!::	;       r6   )Mr   asyncio.streamsr   r  r   collectionsr   
contextlibr   htmlr   r  httpr   loggingr   typingr   r	   r
   r   r   r   r   r   r   r   r   attryarl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__
web_serverr,   _RequestFactory_RequestHandlerURLr   r   r*   r+   r   sr=   _MsgTyper)   r5   r6   r7   <module>r2     s        



                  & & & & & &                                        ; ; ; ; ; ; ; ; ' ' ' ' ' ' ! ! ! ! ! !              + * * * * * - - - - - - - - 0 0 0 0 0 0 0 0 & & & & & & B B B B B B B B ! ! ! ! ! ! $ $ $ $ $ $ 2 2 2 2 2 2 2 2
I #""""""  	 K=)N*CCD		DHSMM	 	! ! ! ! !) ! ! !8 8 8 8 8 8 8 8 +*,,  T$d333       43 ((23\ABE
 E
 E
 E
 E
\ E
 E
 E
 E
 E
r6   