o
    ~#i$a                     @   s  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+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; dZ<erddl=m>Z> ee(e/de dge8f Z?ee8gee; f Z@e(dde'i i ddddeAd
ZBG dd deCZDG dd deCZEeE ZFejGdddd G d!d" d"ZHeee(eHf e/f ZIG d#d de"ZJd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)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__ r3   r3   [/var/www/GraceOrthoHospital/venv_grace/lib/python3.10/site-packages/aiohttp/web_protocol.pyr(   O       r(   c                   @   r-   )r)   z-Payload was accessed after response was sent.Nr.   r3   r3   r3   r4   r)   S   r5   r)   )auto_attribsfrozenslotsc                   @   s&   e Zd ZU eed< eed< eed< dS )_ErrInfostatusexcmessageN)r/   r0   r1   int__annotations__BaseExceptionstrr3   r3   r3   r4   r9   Z   s   
 r9   c                !       sF  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dZdefd d!Zedefd"d#Zd\d%ee dd&fd'd(Zd)e	jdd&f fd*d+Zd,ee dd&f fd-d.Zd/edd&fd0d1Zd]d2d3Zd4edd&fd5d6Z d7edd&fd8d9Z!d]d:d;Z"d]d<d=Z#d>e$d?e%d@edd&fdAdBZ&dCedDedd&fdEdFZ'dCedDedd&fdGdHZ(d]dIdJZ)d>e$dKedLe*e$ge+e% f de,e%ef fdMdNZ-d]dOdPZ.d>e$dQe%dKede,e%ef fdRdSZ/	T	&	&d^d>e$dUed,ee dVee de%f
dWdXZ0dYe1de*e$ge+e% f fdZd[Z2  Z3S )_r'   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_progressg     R@TFi  i   g      $@i      )keepalive_timeoutr    rT   access_log_classrV   access_log_formatrU   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdmanagerr*   loopr]   r    rT   r^   rV   r_   rU   r`   ra   rb   rc   rd   re   rf   c             
      s  t  | d| _d| _d | _|| _|j| _|j| _	|| _
d| _d | _|| _t|| _t | _d| _d | _d | _d | _d| _d | _t| |||
||t|d| _d| _zt|| _W n ttfyc   Y nw || _|	| _|| _ |rv|||| _!nd | _!d| _"d| _#d| _$d S )Nr   Fg            )r`   rb   ra   payload_exceptionre   r\   )%super__init__rA   rB   rY   rC   request_handlerrD   request_factoryrE   rF   rG   rH   rI   floatrJ   r   rK   rL   rN   rM   rO   rP   rQ   r   r(   rR   rZ   	TypeError
ValueErrorrT   rU   rV   r   rW   rX   r[   )selfrg   rh   r]   r    rT   r^   rV   r_   rU   r`   ra   rb   rc   rd   re   rf   	__class__r3   r4   rl      s\   

zRequestHandler.__init__returnc                 C   s    d | jj| jd urdS dS )Nz<{} {}>	connecteddisconnected)formatrt   r/   	transportrr   r3   r3   r4   __repr__   s   zRequestHandler.__repr__c                 C   s   | j S N)rI   rz   r3   r3   r4   r]      s   z RequestHandler.keepalive_timeout      .@timeoutNc              	      s  d| _ | jdur| j  | jr^| j | _z&t|4 I dH  | jI dH  W d  I dH  n1 I dH s7w   Y  W n  tj	tj
fy]   d| _tjdkr[t  }r[| r[ Y nw z@t|4 I dH + | jduru| jt	  | jdur| j st| jI dH  W d  I dH  n1 I dH sw   Y  W n tj	tj
fy   tjdkrt  }r| r Y nw | jdur| 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      )rX   rH   cancelr[   _loopcreate_futurerM   r   asyncioCancelledErrorTimeoutErrorsysversion_infocurrent_task
cancellingrY   _cancelrO   doneshieldforce_close)rr   r~   taskr3   r3   r4   shutdown  sT   

(

	
(


	
zRequestHandler.shutdownry   c                    s   t  | ttj|}| jrt| | jd usJ | j| | | j}t	j
dkr4tj|  |dd}n||  }|| _d S )Nr      Trh   eager_start)rk   connection_mader   r   	TransportrF   r    rC   r   r   r   Taskstartcreate_taskrO   )rr   ry   real_transportrh   r   rs   r3   r4   r   3  s   

zRequestHandler.connection_mader;   c                    s   | j d u rd S | j | | | j j}|   t | d | _ d | _d | _d | _| jd ur2| j	  | j
d urE|d u r?td}| j
| |rQ| jd urQ| j	  d | _| jd urc| j  d | _d S d S )NzConnection lost)rC   connection_losthandler_cancellationr   rk   rE   rD   rR   rH   r   rY   ConnectionResetErrorr   rO   rQ   feed_eof)rr   r;   r   rs   r3   r4   r   D  s.   







zRequestHandler.connection_lostparserc                 C   s6   | j d u sJ || _ | jr| j | j d| _d S d S )Nri   )rQ   rL   	feed_data)rr   r   r3   r3   r4   
set_parserd  s   
zRequestHandler.set_parserc                 C   s   d S r|   r3   rz   r3   r3   r4   eof_receivedn  s   zRequestHandler.eof_receiveddatac           
   
   C   sN  | j s| jrd S | jd u r~| js~| jd usJ z| j|\}}}W n! tyC } ztd||jdt	fg}d}d}W Y d }~nd }~ww |pGdD ]\}}|  j
d7  _
| j||f qH| j}|rn|d urn| sn|d  || _|rz|r||| _d S d S d S | jd u r| jr|r|  j|7  _d S |r| j|\}	}|	r|   d S d S d S )Ni  )r:   r;   r<   Fri   r3   r   )rX   rW   rQ   rP   rR   r   r   r9   r<   r   rA   rK   appendrN   r   
set_resultrL   close)
rr   r   messagesupgradedtailr;   msgpayloadwaitereofr3   r3   r4   data_receivedq  s>   

zRequestHandler.data_receivedvalc                 C   s$   || _ | jr| j  d| _dS dS )zMSet keep-alive connection mode.

        :param bool val: new state.
        N)rB   rH   r   )rr   r   r3   r3   r4   
keep_alive  s
   

zRequestHandler.keep_alivec                 C   s   d| _ | jr| j  dS dS )zClose connection.

        Stop accepting new pipelining messages and close
        connection when handlers done processing messages.
        TN)rW   rN   r   rz   r3   r3   r4   r     s   zRequestHandler.closec                 C   s8   d| _ | jr| j  | jdur| j  d| _dS dS )zForcefully close connection.TN)rX   rN   r   ry   r   rz   r3   r3   r4   r     s   



zRequestHandler.force_closerequestresponsetimec                 C   s,   | j d ur| j ||| j |  d S d S r|   )r   logr   r   )rr   r   r   r   r3   r3   r4   
log_access  s   
zRequestHandler.log_accessargskwc                 O   s    | j r| jj |i | d S d S r|   )rU   rT   rr   r   r   r3   r3   r4   	log_debug  s   zRequestHandler.log_debugc                 O   s   | j j|i | d S r|   )rT   	exceptionr   r3   r3   r4   log_exception  s   zRequestHandler.log_exceptionc                 C   sj   d | _ | js	| jsd S | j}| }| j}||kr#||| j| _ d S | jr1| j	 s3| 
  d S d S d S r|   )rH   rX   rB   r   r   rG   call_at_process_keepaliverN   r   r   )rr   rh   now
close_timer3   r3   r4   r     s   z!RequestHandler._process_keepalive
start_timerm   c              
      s  d| _ zzz|| _||I d H }W d | _nd | _w W nw ty; } z|}| |||I d H \}}W Y d }~ntd }~w tjyC     tjyn } z| jd|d | |d}| |||I d H \}}W Y d }~nAd }~w t	y } z| |d|}| |||I d H \}}W Y d }~nd }~ww t
|ddrtdt | |||I d H \}}W d| _ | jd ur| jd  ||fS d| _ | jd ur| jd  w w )	NTzRequest handler timed out.exc_infoi    __http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception instead)r[   rY   r!   finish_responser   r   r   r   handle_error	ExceptiongetattrwarningswarnDeprecationWarningrM   r   )rr   r   r   rm   respr;   resetr3   r3   r4   _handle_request  sL   $$$

zRequestHandler._handle_requestc              
      s<  | j }t|}|dusJ | j}|dusJ | j}d}| jdus$J | jdus+J | js| jsGz|	 | _
| j
I dH  W d| _
nd| _
w | j \}}| }| jd7  _t| |}	t|trk| |}
t}n| j}
| ||| |	|}zȐz[| |||
}tjdkrtj||dd}n||}z	|I dH \}}W nJ ty   | d Y W W | jdu r|dur| d n| js| jr| js|dur| }|| }|| _| jdu r||| j | _nnnw ~|r6| d W W | jdu r|dur| d n| js4| jr2| js2|dur0| }|| }|| _| jdu r0||| j | _nTnRnPt!|j"| _|# s| j$}| js|r| d	| | }|| }zB|# s||k rt%|| 4 I dH  |& I dH  W d  I dH  n1 I dH sw   Y  | }|# s||k sdW n! tj'tj(fy   tjd
krt  }r|) r Y nw |# s| js| d | *  |+t, W n, tj'y   | d   t-y } z| j.d|d | /  W Y d}~nd}~ww W | jdu r|dur| d no| js@| jr?| js?|dur>| }|| }|| _| jdu r>||| j | _nDnFnB| jdu rR|durR| d w | js| jr}| js}|dur|| }|| }|| _| jdu r|||| j | _w    Y nw | jr/| jsd| _0| jdur| 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   rC   rI   rE   rD   rX   rK   r   rN   popleftr   requests_countr   
isinstancer9   _make_error_handlerERRORr   r   r   r   r   ConnectionErrorr   ry   rB   rW   rG   rH   r   r   boolr   is_eofrJ   r   readanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rO   )rr   rh   handlerrg   r]   r   r<   r   r   writerrm   r   coror   r   r   r   rc   end_ttr;   r3   r3   r4   r     s"  	







2

,

*
	




ezRequestHandler.startr   c              	      s  |   | jdur | jd d| _| jr | j| j d| _z|j}W n- tyR   |du r6| d n| d	| t
 }t|j|j|j|jd}|j}Y nw z||I dH  | I dH  W n tyw   | ||| |df Y S 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.
        NFri   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r})r:   reasontextheadersT)_finishrR   set_upgradedrP   rL   r   prepareAttributeErrorr   rx   r"   r%   r:   r   r   r   	write_eofr   r   )rr   r   r   r   prepare_methr;   r3   r3   r4   r   {  s@   



zRequestHandler.finish_responser   r:   r<   c           
      C   s   | j d|d |jjdkrtdd}|tjkrhdtj}tjj}d}| jr?t	t
 t }W d   n1 s:w   Y  d|jd	d
v r^|rTt|}d| d}dj||d}d}n
|rb|}|d | }t|||d}	|	  |	S )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:   r   content_type)r   r   output_sizer   r   INTERNAL_SERVER_ERRORrx   descriptionrU   r   r   	traceback
format_excr   gethtml_escaper%   r   )
rr   r   r:   r;   r<   ctr   r   tbr   r3   r3   r4   r     s8   


zRequestHandler.handle_errorerr_infoc                    s   dt dtf fdd}|S )Nr   ru   c                    s    |  j j jS r|   )r   r:   r;   r<   )r   r   rr   r3   r4   r     s   z3RequestHandler._make_error_handler.<locals>.handler)r$   r&   )rr   r   r   r3   r   r4   r     s   z"RequestHandler._make_error_handler)r}   )ru   N)r   NN)4r/   r0   r1   r2   	__slots__r   r#   r   
LOG_FORMATr   AbstractEventLoopro   r   r   r   r   r@   r=   rl   r{   propertyr]   r   r   BaseTransportr   r?   r   r   r   r   bytesr   r   r   r   r$   r&   r   r   r   r   r
   r	   r   r   r   r   r   r9   r   __classcell__r3   r3   rs   r4   r'   d   s    '$	
L2 

'



	




+}

-
3)Kr   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   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   sr9   _MsgTyper'   r3   r3   r3   r4   <module>   sr    4