
    yiZ                     j   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*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 dZ:erddl;m<Z< ee'e.dedge6f   Z=ee6gee9   f   Z> e'dde&i i dddd ej~                  d      
      Z@ G d deA      ZB G d deA      ZC ej                  ddd        G d! d"             ZEeee'eEf   e.f   ZF G d# de!      ZGy)$    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)access_loggerserver_logger)EMPTY_PAYLOADStreamReader)tcp_keepalive)HTTPException)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__     O/root/polymarket_arb/.venv/lib/python3.12/site-packages/aiohttp/web_protocol.pyr(   r(   N   s     r4   r(   c                       e Zd ZdZy)r)   z-Payload was accessed after response was sent.Nr.   r3   r4   r5   r)   r)   R   s    7r4   r)   )auto_attribsfrozenslotsc                   ,    e Zd ZU eed<   eed<   eed<   y)_ErrInfostatusexcmessageN)r/   r0   r1   int__annotations__BaseExceptionstrr3   r4   r5   r;   r;   V   s    K	Lr4   r;   c            !       l    e Zd 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dFd"ee   dd#fd$Zd%e
j2                  dd#f fd&Zd'ee   dd#f fd(Zd)edd#fd*ZdGd+Zd,e dd#fd-Z!d.edd#fd/Z"dGd0Z#dGd1Z$d2e%d3e&d4edd#fd5Z'd6ed7edd#fd8Z(d6ed7edd#fd9Z)dGd:Z*d2e%d;ed<e+e%ge,e&   f   de-e&ef   fd=Z.dGd>Z/d2e%d?e&d;edefd@Z0	 	 	 dHd2e%dAed'ee   dBee   de&f
dCZ1dDe2de+e%ge,e&   f   fdEZ3 xZ4S )Ir'   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

    r   )_request_count
_keepalive_manager_request_handler_request_factory_tcp_keepalive_keepalive_time_keepalive_handle_keepalive_timeout_lingering_time	_messages_message_tail_waiter_task_handler_upgrade_payload_parser_request_parser_reading_pausedloggerdebug
access_logr   _close_force_close_current_request_timeout_ceil_thresholdg     R@TFi  i   g      $@i      )keepalive_timeoutr!   rV   access_log_classrX   access_log_formatrW   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdmanagerr*   loopr^   r!   rV   r_   rX   r`   rW   ra   rb   rc   rd   re   rf   rg   c          
      d   t         |   |       d| _        d| _        d | _        || _        |j                  | _        |j                  | _	        || _
        d| _        d | _        || _        t        |      | _        t!               | _        d| _        d | _        d | _        d| _        d | _        t/        | |||
||t0        |      | _        d| _        	 t        |      | _        || _        |	| _        || _        |r |||      | _         nd | _         d| _!        d| _"        y # t6        t8        f$ r Y Mw xY w)Nr   Fg        r4   )ra   rc   rb   payload_exceptionrf   r]   )#super__init__rD   rE   r[   rF   request_handlerrG   request_factoryrH   rI   rJ   rK   rL   floatrM   r   rN   rO   rP   rQ   rR   rS   r   r(   rT   r\   	TypeError
ValueErrorrV   rW   rX   r   rY   rZ   )selfrh   ri   r^   r!   rV   r_   rX   r`   rW   ra   rb   rc   rd   re   rf   rg   	__class__s                    r5   rm   zRequestHandler.__init__   sJ   ( 	7;*1;B;R;R;B;R;R+";?"3$^4*/' 7;;?$(<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)formatrt   r/   	transportrs   s    r5   __repr__zRequestHandler.__repr__   s;    NN##>>5K
 	
;I
 	
r4   c                     | j                   S N)rL   r{   s    r5   r^   z RequestHandler.keepalive_timeout   s    &&&r4   timeoutNc                 8  K   d| _         | j                  | j                  j                          | j                  r| j                  j                          t	        t
        j                  t
        j                        5  t        |      4 d{    | j                  -| j                  j                  t        j                                | j                  .| j                  j                         s| j                   d{    ddd      d{    ddd       | j                  | j                  j                          | j                  "| j                  j                          d| _        yy7 7 s7 e# 1 d{  7  sw Y   uxY w# 1 sw Y   yx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)rZ   rK   cancelrP   r   asyncioCancelledErrorTimeoutErrorr   r[   _cancelrQ   donerz   close)rs   r   s     r5   shutdownzRequestHandler.shutdown   sJ     !!!-""))+<<LL! g,,g.B.BC 	-#G, - -((4))11'2H2H2JK%%1$:L:L:Q:Q:S,,,,- -	- )%%'>>%NN  "!DN &-
 -- - - -	- 	-sz   A<F>FE3FA/E9E5E9FE7FAF3F5E97F9F	?F F	FFFrz   c                 6   t         |   |       t        t        j                  |      }| j
                  rt        |       | j                  j                  | j                               | _
        | j                  J | j                  j                  | |       y r~   )rl   connection_mader   r   	TransportrI   r!   _loopcreate_taskstartrQ   rF   )rs   rz   real_transportrt   s      r5   r   zRequestHandler.connection_made  st    	*g//;.)!ZZ33DJJLA}}(((%%dN;r4   r=   c                    | j                   y | j                   j                  | |       t        |   |       | j                   j                  }d | _         d| _        d | _        d | _        d | _        | j                  | j                  j                          | j                  (|t        d      }| j                  j                  |       | j                  | j                  j                          |r&| j                  | j                  j                          d | _        | j                  "| j                  j!                          d | _        y y )NTzConnection lost)rF   connection_lostrl   handler_cancellationrZ   rH   rG   rT   rK   r   r[   ConnectionResetErrorr   rP   rQ   rS   feed_eof)rs   r=   r   rt   s      r5   r   zRequestHandler.connection_lost%  s%   == %%dC0$  $}}AA  $ $#!!-""))+  ,{*+<=!!))#.<<#LL!D$6$6$B%%'!+  ))+#'D  ,r4   parserc                     | j                   J || _         | j                  r-| j                   j                  | j                         d| _        y y )Nr4   )rS   rO   	feed_data)rs   r   s     r5   
set_parserzRequestHandler.set_parserI  sL    ##+++%  **4+=+=>!$D r4   c                      y r~   r3   r{   s    r5   eof_receivedzRequestHandler.eof_receivedS  s    r4   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>   Fr4   r3   r   )rZ   rY   rS   rR   rT   r   r   r;   r>   r   rD   rN   appendrP   r   
set_resultrO   r   )
rs   r   messagesupgradedtailr=   msgpayloadwaitereofs
             r5   data_receivedzRequestHandler.data_receivedV  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)rE   rK   r   )rs   r   s     r5   
keep_alivezRequestHandler.keep_alive}  s3    
 !!""))+%)D" "r4   c                 `    d| _         | j                  r| j                  j                          yy)zClose connection.

        Stop accepting new pipelining messages and close
        connection when handlers done processing messages.
        TN)rY   rP   r   r{   s    r5   r   zRequestHandler.close  s'     <<LL! r4   c                     d| _         | j                  r| j                  j                          | j                  "| j                  j	                          d| _        yy)zForcefully close connection.TN)rZ   rP   r   rz   r   r{   s    r5   force_closezRequestHandler.force_close  sG     <<LL!>>%NN  "!DN &r4   requestresponsetimec                     | j                   9| j                   j                  ||| j                  j                         |z
         y y r~   )r   logr   r   )rs   r   r   r   s       r5   
log_accesszRequestHandler.log_access  s=     )""7Hdjjoo6G$6NO *r4   argskwc                 V    | j                   r | j                  j                   |i | y y r~   )rW   rV   rs   r   r   s      r5   	log_debugzRequestHandler.log_debug  s'    ::DKKt*r* r4   c                 <     | j                   j                  |i | y r~   )rV   	exceptionr   s      r5   log_exceptionzRequestHandler.log_exception  s    t*r*r4   c                 F   | j                   s| j                  sy | j                  | j                  z   }| j                  r.| j
                  j                         |kD  r| j                          y | j
                  j                  | j                  | j                        | _        y r~   )rZ   rE   rJ   rL   rP   r   r   r   
call_laterKEEPALIVE_RESCHEDULE_DELAY_process_keepaliverK   )rs   nexts     r5   r   z!RequestHandler._process_keepalive  s    DOO##d&=&== <<zz 4'  " "&!6!6++##"
r4   
start_timern   c                   K   | j                   J 	 	 || _         ||       d {   }d | _        	 t        |dd      rt        j                  dt
               | j                  |||       d {   }||fS 7 R# d | _        w xY w7 # t        $ r+}|}| j                  |||       d {  7  }Y d }~||fS d }~wt        j                  $ r  t        j                  $ rN}| j                  d|       | j                  |d      }| j                  |||       d {  7  }Y d }~||fS d }~wt        $ r<}| j                  |d|      }| j                  |||       d {  7  }Y d }~||fS d }~ww xY ww)N__http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception insteadzRequest handler timed out.exc_infoi    )rG   r[   getattrwarningswarnDeprecationWarningfinish_responser"   r   r   r   r   handle_error	Exception)rs   r   r   rn   respresetr=   s          r5   _handle_requestzRequestHandler._handle_request  s     $$000	J-(/%,W55(,% t1599 '	 ..wjIIEU{7 6(,%. J-  	JD..wjIIIE, U{+ %% 	## 	JNN7#NF$$Wc2D..wjIIIE  U{  	J$$Wc37D..wjIIIE U{	Js   E4A: A8A: B =E4/B0E48A: :	BB E4	E1B7)B,*B7/E47)E1 ;D)DD)!E4)E15)E,E!E,$E4,E11E4c                   K   | j                   }| j                  }|J | j                  }|J | j                  }d}| j                  J | j
                  J | j                  s| j                  s2	 |j                         | _	        | j                   d{    	 d| _	        | j                  j                         \  }}|j                         }|xj                  dz  c_        t        | |      }	t!        |t"              r| j%                  |      }
t&        }n| j
                  }
| j	                  ||| |	|      }	 | j                   j)                  | j+                  |||
            }	 | d{   \  }}~|r| j/                  d       	 | j0                  || j/                  d       n| j                  s| j2                  rc| j4                  sW|j| j                   j                         }|| _        | j8                  <|j;                  ||z   | j<                        | _        nnt?        |j@                        | _        |jC                         s)| jD                  }| j                  s|r| j/                  d|       |j                         }||z   }tG        t        jH                  t        j                        5  |jC                         sj||k  retK        ||z
        4 d{    |jM                          d{    ddd      d{    |j                         }|jC                         s||k  reddd       |jC                         s-| j                  s!| j/                  d       | jO                          |jQ                  tS                      | j0                  || j/                  d       ny| j                  sm| j2                  r`| j4                  sT|S| j                   j                         }|| _        | j8                  &|j;                  ||z   | j<                        | _        nn| j                  s| j                  s/d| _        | j0                  | j0                  jO                          yyy7 # t        j                  $ r
 Y d| _	        [w xY w# d| _	        w xY w7 ;# t        j                  t,        f$ r | j/                  d       Y | j0                  || j/                  d       | j                  r| j2                  rd| j4                  sX|| j                   j                         }|| _        | j8                  |j;                  ||z   | j<                        | _        68w xY w7 7 7 r# 1 d{  7  sw Y   xY w# 1 sw Y   bxY w# t        j                  $ r | j/                  d       Y | j0                  || j/                  d       | j                  r| j2                  re| j4                  sY|| j                   j                         }|| _        | j8                  |j;                  ||z   | j<                        | _        -/tT        $ r:}| jV                  r| jY                  d	|
       | j[                          Y d}~d}~wt\        $ r.}| jY                  d|
       | j[                          Y d}~Hd}~ww xY w# | j0                  || j/                  d       w | j                  sr| j2                  rb| j4                  sV|S| j                   j                         }|| _        | j8                  %|j;                  ||z   | j<                        | _        w w w  Y Hw 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   z&Ignored premature client disconnectionz'Ignored premature client disconnection.z(Ignored premature client disconnection 2z'Start lingering close timer for %s sec.zUncompleted request.z'Ignored premature client disconnection zUnhandled runtime exceptionr   zUnhandled exception)/r   rQ   rF   rL   rH   rG   rZ   rN   create_futurerP   r   r   popleftr   requests_countr   
isinstancer;   _make_error_handlerERRORr   r   ConnectionErrorr   rz   rE   rY   rJ   rK   call_atr   boolr   is_eofrM   r   r   r   readanyr   set_exceptionr)   RuntimeErrorrW   r   r   r   )rs   ri   handlerrh   r^   r   r>   r   r   writerrn   r   taskr   nowrd   end_tr=   s                     r5   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++GWdFGTGEzz--((%I(,*KD% NN#MNR >>)d.>NN#LM**t{{,8"&**//"3C36D0#55=9=$'*;$;T=T=T:" 6 g #'t"7 ~~'%)%9%9N,,E~ #iik #n 4%g&:&:G<R<RS 2&-nn&63;+7+D !< !<*1//*;$;$;!< !< '+iik	 '.nn&63;2 #>>+D4E4E'=>

%%&8&:; >>)d.>NN#LM**t{{,8"&**//"3C36D0#55=9=$'*;$;T=T=T:" 6 } ##B   !%D~~)$$& * !y '-- #'DL $(DL, #-..@ NN#KL^ >>)d.>NN#LM**t{{,8"&**//"3C36D0#55=9=$'*;$;T=T=T:" 6 }4!<$;!< !< !< !<2 2 )) HI >>)d.>NN#LM**t{{,8"&**//"3C36D0#55=9=$'*;$;T=T=T:" 6 +   #::&&'Ds&S  "" #""#83"G  ""# >>)d.>NN#LM**t{{,8"&**//"3C36D0#55=9=$'*;$;T=T=T:" 6  > 9  +s  A0^
3$Q= Q:Q= B^
<,V& )R, .R)/R, 6V& B^
*BV& >(V&U:'V*V>U=?VVV )V9AV& B%^
><^
:Q= =RR ^
RR 	R&&^
)R, ,*U7V& ,^
^
-^
(^
6U77V& :V=V VV		V
V	VV#V& &$[$
[' -^
:^
-^
(^
-[$5/Z*$[' *[$6#[[' [$$[' 'B^^
^^
r   c                   K   | j                   Z| j                   j                  d       d| _        | j                  r,| j                   j	                  | j                         d| _        	 |j
                  }	  ||       d{    |j                          d{    | j                  |||       y# t        $ r( |t        d      t        dj                  |            w xY w7 d7 N# t        $ r | j                  |||       Y y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.
        NFr4   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r}T)rT   set_upgradedrR   rO   r   prepareAttributeErrorr   ry   	write_eofr   r   )rs   r   r   r   prepare_meths        r5   r   zRequestHandler.finish_responseZ  s     +  --e4!DM!!$$..t/A/AB%("
	<<L	w'''.."""
 OOGT:6#  	|"#STT"%vd| 		 (" 	OOGT:6	s`   A'D*B3 7C+ C'C+ C)C+ D31C$$D'C+ )C+ +D
D	D

Dr<   r>   c                 ~   | j                  d|       |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.
        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<   textcontent_type)r   r   output_sizer   r   INTERNAL_SERVER_ERRORry   descriptionrW   r   r   	traceback
format_excheadersgethtml_escaper%   r   )
rs   r   r<   r=   r>   ctr   r   tbr   s
             r5   r   zRequestHandler.handle_error  s<    	3cB >>%%)!) 
 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   #D33D<err_infoc                 0     dt         dt        f fd}|S )Nr   ru   c                 p   K   j                  | j                  j                  j                        S wr~   )r   r<   r=   r>   )r   r   rs   s    r5   r   z3RequestHandler._make_error_handler.<locals>.handler  s1     $$(,,8H8H s   36)r$   r&   )rs   r   r   s   `` r5   r   z"RequestHandler._make_error_handler  s    	; 	> 	
 r4   )g      .@)ru   N)r   NN)5r/   r0   r1   r2   r   	__slots__r   r#   r   
LOG_FORMATr   AbstractEventLooprp   r   r   r   r   rB   r?   rm   r|   propertyr^   r   r   BaseTransportr   rA   r   r	   r   r   bytesr   r   r   r   r$   r&   r   r   r   r   r   r
   r   r   r   r   r   r;   r   __classcell__)rt   s   @r5   r'   r'   `   s   %N "#ID $("&7C*!-!8!8! " $! $()%H"H" ''	H"
 !H" H" H" 34H" H" H" H" H" H" H" H"  !H"" #H"$ !&%H"T
# 
 '5 ' '"huo " ">	<)>)> 	<4 	<"(8M#: "(t "(H% % %%% %D %N*d *t *""P"P.<PDIP	P+s +# +$ ++3 +c +d +
&%% % ";->1J"JK	%
 
~t#	$%Nw'r#"#*8#FK#	#P '+!%11 1 m$	1
 #1 
1f 	;->!::	;r4   )Hr   asyncio.streamsr   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   r   r   r   streamsr   r    tcp_helpersr!   web_exceptionsr"   web_logr#   web_requestr$   web_responser%   r&   __all__
web_serverr*   _RequestFactory_RequestHandlerURLr   r   r(   r)   sr;   _MsgTyper'   r3   r4   r5   <module>r     sO         &        ; ' !  . 0 & ) ! $ 2
I"  	 K=)N*CCD		DHHSM	!) !8 8 T$d3  4 ((23\ABZ	\ Z	r4   