
    $Gg>e                        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j                  d      
      ZD G d deE      ZF G d d eE      ZG eG       ZH ej                  ddd!       G d" d#             ZJeee(eJf   e1f   ZK G d$ de"      ZLy)%    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y)r*   zPayload parsing error.N__name__
__module____qualname____doc__     q/home/kushmeetdev/apache_webroot/langgraph_flaskproject/venv/lib/python3.12/site-packages/aiohttp/web_protocol.pyr*   r*   P   s     r6   r*   c                       e Zd ZdZy)r+   z-Payload was accessed after response was sent.Nr0   r5   r6   r7   r+   r+   T   s    7r6   r+   )auto_attribsfrozenslotsc                   ,    e Zd ZU eed<   eed<   eed<   y)_ErrInfostatusexcmessageN)r1   r2   r3   int__annotations__BaseExceptionstrr5   r6   r7   r=   r=   [   s    K	Lr6   r=   c            !       r    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dEd!ee   dd"fd#Zd$e	j0                  dd"f fd%Zd&ee   dd"f fd'Zd(edd"fd)ZdFd*Zd+edd"fd,Z d-edd"fd.Z!dFd/Z"dFd0Z#d1e$d2e%d3edd"fd4Z&d5ed6edd"fd7Z'd5ed6edd"fd8Z(dFd9Z)d1e$d:ed;e*e$ge+e%   f   de,e%ef   fd<Z-dFd=Z.d1e$d>e%d:ede,e%ef   fd?Z/	 	 	 dGd1e$d@ed&ee   dAee   de%f
dBZ0dCe1de*e$ge+e%   f   fdDZ2 xZ3S )Hr)   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        |      | _        || _        |	| _        || _         |r |||      | _!        nd | _!        d| _"        d| _#        d| _$        y # t8        t:        f$ r Y Tw xY w)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;R;B;R;R+*-';?"3$^4*/' 7;?C;?$(<M')#1+	=
 /0$	+01G+HD( 
$AQ-BD "&D!$)! :& 		s   D+ +D=<D=returnc                 r    dj                  | j                  j                  | j                  d      S d      S )Nz<{} {}>	connecteddisconnected)formatrx   r1   	transportrw   s    r7   __repr__zRequestHandler.__repr__   s;    NN##>>5K
 	
;I
 	
r6   c                     | j                   S N)rN   r   s    r7   rb   z RequestHandler.keepalive_timeout   s    &&&r6   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]   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  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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;zzw&<<

4TJD " ##DJJL1D!r6   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)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  s   == %%dC0  $}}AA$ $ $#!!-""))+  ,{*+<=!!))#.D$6$6$B%%'!+  ))+#'D  ,r6   parserc                     | j                   J || _         | j                  r-| j                   j                  | j                         d| _        y y )Nr6   )rV   rQ   	feed_data)rw   r   s     r7   
set_parserzRequestHandler.set_parserg  sL    ##+++%  **4+=+=>!$D r6   c                      y r   r5   r   s    r7   eof_receivedzRequestHandler.eof_receivedq  s    r6   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?   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  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)rG   rM   r   )rw   r   s     r7   
keep_alivezRequestHandler.keep_alive  s3    
 !!""))+%)D" "r6   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\   rS   r   r   s    r7   r   zRequestHandler.close  s'     <<LL! r6   c                     d| _         | j                  r| j                  j                          | j                  "| j                  j	                          d| _        yy)zForcefully close connection.TN)r]   rS   r   r~   r   r   s    r7   r   zRequestHandler.force_close  sG     <<LL!>>%NN  "!DN &r6   requestresponsetimec                     | j                   P| j                   j                  r9| j                   j                  ||| j                  j	                         |z
         y y y r   )r   enabledlogr   r   )rw   r   r   r   s       r7   
log_accesszRequestHandler.log_access  sO     )d.@.@.H.H""7Hdjjoo6G$6NO /I)r6   argskwc                 V    | j                   r | j                  j                   |i | y y r   )rZ   rY   rw   r   r   s      r7   	log_debugzRequestHandler.log_debug  s'    ::DKKt*r* r6   c                 <     | j                   j                  |i | y r   )rY   	exceptionr   s      r7   log_exceptionzRequestHandler.log_exception  s    t*r*r6   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   )rM   r]   rG   r   r   rL   call_at_process_keepaliverS   r   r   )rw   rm   now
close_times       r7   r   z!RequestHandler._process_keepalive  s    !%DOOzziik44
%)\\*d>U>U%VD" << 1 1 3 !4<r6   
start_timerr   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    )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(,% 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
                  sm| j                  s1	 |j                         | _        | j                   d{    d| _        | j                  j                         \  }}|j                         }|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%        j.                  ||d      }n|j1                  |      }	 | d{   \  }}~|r<| j5                  d       	 d|
_        | j8                  || j5                  d       nt;        |j<                        | _        |jA                         s| jB                  }| j
                  s|r| j5                  d	|       |j                         }||z   }	 |jA                         sj||k  retE        ||z
        4 d{    |jG                          d{    ddd      d{    |j                         }|jA                         s||k  re|jA                         s-| j
                  s!| j5                  d       | jO                          |jQ                  tR               d|
_        | j8                  || j5                  d       	 | j>                  r`| j\                  sT| j
                  sH|j                         |z   }|| _/        | j`                  #|jc                  || jd                        | _0        nn| j
                  sm| j
                  s/d| _        | j8                  | j8                  jO                          yyy7 x# d| _        w xY w7 l# t2        $ r< | j5                  d       Y d|
_        | j8                  }|| j5                  d       w xY w7 7 7 # 1 d{  7  sw Y   xY w# t$        jH                  t$        jJ                  f$ r> t*        j,                  d
k\  r't%        j&                         x}r|jM                         r Y 	w xY w# t$        jH                  $ r# | j5                  d       | jU                           tV        $ r.}| jY                  d|       | jU                          Y d}~!d}~wtZ        $ r | jU                           w xY w# d|
_        | j8                  || j5                  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   )3r   rH   rN   rJ   rI   r]   rP   r   rS   popleftr   requests_countr   
isinstancer=   _make_error_handlerERRORrT   r   r   r   r   r   r   r   ConnectionErrorr   _taskr~   boolr   rG   is_eofrO   r   readanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rC   r\   rL   rM   r   r   )rw   rm   rl   rb   r   r@   r   r   writerrr   r   coror   r   rh   r   end_ttr?   r   s                       r7   r   zRequestHandler.start  s     zz--""" 33$$000$$000##>>(#'#5#5#7DL,,&&#'DL#~~557GWIIKE""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* ] ##b   !%D~~)$$& * !Y '#'DLB #-& 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 O?P B?VAS P "P#P *S ?*V)A+S 'Q8 <Q=Q8  Q"QQ"Q8 $Q%)Q8 AS !B V<V?P 	PVP Q+S ,V VVQS Q8 Q"Q8 "Q5(Q+)Q50Q8 8ASS SS =U #U<U# U  U# #*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.
        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!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>   r@   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)rF   r   r   rY   rZ   remoter   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
 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   ry   c                 p   K   j                  | j                  j                  j                        S wr   )r   r>   r?   r@   )r   r  rw   s    r7   handlerz3RequestHandler._make_error_handler.<locals>.handler  s1     $$(,,8H8H s   36)r&   r(   )rw   r  r  s   `` r7   r   z"RequestHandler._make_error_handler  s    	; 	> 	
 r6   )g      .@)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!8! " $! $()'L*L* ''	L* !L* L* L* 34L* L* L* L* L* L* L*  !L*" #L*$ %L*& !&'L*\
# 
 '5 ' '0huo 0 0d")>)> "4 ""(8M#: (t (@% % %%% %D %N*d *t *""P"P.<PDIP	P+s +# +$ ++3 +c +d +")) ) ";->1J"JK	)
 
~t#	$)VE'N("(*8(FK(	~t#	$(Z '+!%<< < m$	<
 #< 
<| 	;->!::	;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>r3     s`     
     &        ; ' !  + - 0 & B ! $ 2
I"  	 K=)N*CCD		DHHSM	!) !8 8 +,  T$d3  4 ((23\ABS
\ S
r6   