
    `KhT              	       X   U d dl Z d dlZd dlZ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	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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& ddl'm(Z( ddl)m*Z*m+Z+ dZ,dZ-ee.   e/d<   dZ0ee.   e/d<    e1       Z2ee jf                  d      e/d<    G d de4      Z5 G d de6ejn                        Z8dedededdfdZ9e8jt                  dded   ded e8ddfd!Z; G d" d#      Z<ed   Z=ee=ef   Z> G d$ d%      Z? G d& de	      Z@ G d' d(e@      ZA G d) d*eA      ZB G d+ d,eB      ZC G d- d.e@      ZD G d/ d0eD      ZE G d1 d2eD      ZF G d3 d4eD      ZG G d5 d6eA      ZHerd d7lmIZImJZJ eJeK   ZLeIeK   ZMnd d7lmIZImJZJ eJZLeIZM G d8 d9e@      ZN G d: d;eN      ZO e?       ZPePj                  eAeKeReSf       ePj                  eBe6       ePj                  eCej                         ePj                  eEej                         ePj                  eFej                         ePj                  eGej                  ej                  f       ePj                  eDej                         ePj                  eOe(       ePj                  eNeIe8j                         y)<    N)ABCabstractmethod)Iterable)chain)IOTYPE_CHECKINGAnyDictFinalListOptionalSetTextIOTupleTypeUnion)CIMultiDict   )hdrs)AbstractStreamWriter)	_SENTINELcontent_disposition_headerguess_filenameparse_mimetypesentinel)StreamReader)JSONEncoder_CIMultiDict)PAYLOAD_REGISTRYget_payloadpayload_typePayloadBytesPayloadStringPayloadIOBasePayloadBytesIOPayloadBufferedReaderPayloadTextIOPayloadStringIOPayloadJsonPayloadAsyncIterablePayloadi   TOO_LARGE_BYTES_BODYi   	READ_SIZE_CLOSE_FUTURESc                       e Zd ZdZy)LookupErrorz@Raised when no payload factory is found for the given data type.N)__name__
__module____qualname____doc__     m/var/www/CtrlAgent-Voice-Telephony-Channel/python-server/venv/lib/python3.12/site-packages/aiohttp/payload.pyr0   r0   >   s    Jr6   r0   c                       e Zd ZdZdZdZy)Ordernormal	try_firsttry_lastN)r1   r2   r3   r:   r;   r<   r5   r6   r7   r9   r9   B   s    FIHr6   r9   dataargskwargsreturnr"   c                 4    t        j                  | g|i |S N)r   get)r=   r>   r?   s      r7   r    r    H   s    6t6v66r6   orderfactorytyperE   c                4    t         j                  | ||       y NrD   )r   register)rF   rG   rE   s      r7   register_payloadrK   L   s     gt59r6   c                   V    e Zd Zej                  ddededdfdZded   ded   fd	Zy)
r!   rD   rG   rE   r@   Nc                     || _         || _        y rB   )rG   rE   )selfrG   rE   s      r7   __init__zpayload_type.__init__S   s    	
r6   rF   r"   c                 J    t        || j                  | j                         |S rI   )rK   rG   rE   )rN   rF   s     r7   __call__zpayload_type.__call__W   s    $))4::>r6   )	r1   r2   r3   r9   r:   r	   rO   r   rQ   r5   r6   r7   r!   r!   R   s>    49LL S E T Y DO r6   r!   c                   p    e Zd ZdZdZddZeddeded	d
deddf
dZe	j                  ddedede	ddfdZy)PayloadRegistryzZPayload registry.

    note: we need zope.interface for more efficient adapter search
    _first_normal_last_normal_lookupr@   Nc                 <    g | _         g | _        g | _        i | _        y rB   rT   rN   s    r7   rO   zPayloadRegistry.__init__h   s    243513
68r6   )_CHAINr=   r>   r[   z!Type[chain[_PayloadRegistryItem]]r?   r"   c                   | j                   r.| j                   D ]  \  }}t        ||      s ||g|i |c S  | j                  j                  t	        |            x}r ||g|i |S t        |t
              r|S  || j                  | j                        D ]  \  }}t        ||      s ||g|i |c S  t               rB   )	rU   
isinstancerX   rC   rG   r"   rV   rW   r0   )rN   r=   r[   r>   r?   rF   type_lookup_factorys           r7   rC   zPayloadRegistry.getn   s     ;;"&++ :dE*"49$9&99: "0044T$Z@@>@!$8888dG$K$T\\4::> 	6NGU$&t5d5f55	6 mr6   rD   rF   rG   rE   c                   |t         j                  u r| j                  j                  ||f       y |t         j                  u rT| j
                  j                  ||f       t        |t              r|D ]  }|| j                  |<    y || j                  |<   y |t         j                  u r| j                  j                  ||f       y t        d|      )NzUnsupported order )r9   r;   rU   appendr:   rV   r]   r   rX   r<   rW   
ValueError)rN   rF   rG   rE   ts        r7   rJ   zPayloadRegistry.register   s     EOO#KK/ell"LL$0$) 5A-4D''*5 -4##D)enn$JJwo.1%;<<r6   r@   N)r1   r2   r3   r4   	__slots__rO   r   r	   rC   r9   r:   PayloadTyperJ   r5   r6   r7   rS   rS   `   s~    
 AI9 7<	  4	
  
0 BG="=*-=9>=	=r6   rS   c                      e Zd ZU dZeed<   dZee   ed<   dZ	e
ed<   dZe
ed<   deddfded	eeeeeef   eeeef      f      d
eedef   dee   dee   deddfdZedee   fd       Zedee   fd       Zedefd       Zedefd       Zedee   fd       Zedefd       Zede
fd       Zede
fd       Z	 	 d&dede
dededdf
dZe d'dededefd       Z!e de"ddfd        Z#de"d!ee   ddfd"Z$d'dededefd#Z%d(d$Z&d(d%Z'y))r"   application/octet-stream_default_content_typeN_sizeF	_consumed
_autoclosevalueheaderscontent_typefilenameencodingr?   r@   c                 (   || _         || _        t               | _        || _        |t
        ur ||| j                  t        j                  <   n| j                  ut        j                  dk\  rt        j                  }nt        j                  } || j                        d   }|| j                  }|| j                  t        j                  <   n'| j                  | j                  t        j                  <   |r| j                  j                  |       y y )N)      r   )	_encoding	_filenamer   _headers_valuer   r   CONTENT_TYPEsysversion_info	mimetypesguess_file_type
guess_typeri   update)rN   rm   rn   ro   rp   rq   r?   guessers           r7   rO   zPayload.__init__   s     "!&1mx'L,D/;DMM$++,^^'7*#33#.."4>>215L##99/;DMM$++,/3/I/IDMM$++,MM  ) r6   c                     | j                   S )zSize of the payload in bytes.

        Returns the number of bytes that will be transmitted when the payload
        is written. For string payloads, this is the size after encoding to bytes,
        not the length of the string.
        rj   rZ   s    r7   sizezPayload.size   s     zzr6   c                     | j                   S )zFilename of the payload.)rv   rZ   s    r7   rp   zPayload.filename        ~~r6   c                     | j                   S )zCustom item headers)rw   rZ   s    r7   rn   zPayload.headers   s     }}r6   c                     dj                  | j                  j                         D cg c]  \  }}|dz   |z   dz    c}}      j                  d      dz   S c c}}w )N z: z
utf-8s   
)joinrn   itemsencode)rN   kvs      r7   _binary_headerszPayload._binary_headers   sY     GGt||7I7I7KLtq!QX\F*LMTT 	
Ls   A
c                     | j                   S )zPayload encoding)ru   rZ   s    r7   rq   zPayload.encoding   r   r6   c                 <    | j                   t        j                     S )zContent type)rw   r   ry   rZ   s    r7   ro   zPayload.content_type   s     }}T..//r6   c                     | j                   S )z;Whether the payload has been consumed and cannot be reused.)rk   rZ   s    r7   consumedzPayload.consumed   r   r6   c                     | j                   S )z
        Whether the payload can close itself automatically.

        Returns True if the payload has no file handles or resources that need
        explicit closing. If False, callers must await close() to release resources.
        )rl   rZ   s    r7   	autoclosezPayload.autoclose   s     r6   disptypequote_fields_charsetparamsc                 X    t        |f||d|| j                  t        j                  <   y)z$Sets ``Content-Disposition`` header.)r   r   N)r   rw   r   CONTENT_DISPOSITION)rN   r   r   r   r   s        r7   set_content_dispositionzPayload.set_content_disposition   s3     3M3
#/(3
FL3
d../r6   errorsc                      y)z
        Return string representation of the value.

        This is named decode() to allow compatibility with bytes objects.
        Nr5   rN   rq   r   s      r7   decodezPayload.decode       r6   writerc                    K   yw)a  
        Write payload to the writer stream.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing

        This is a legacy method that writes the entire payload without length constraints.

        Important:
            For new implementations, use write_with_length() instead of this method.
            This method is maintained for backwards compatibility and will eventually
            delegate to write_with_length(writer, None) in all implementations.

        All payload subclasses must override this method for backwards compatibility,
        but new code should use write_with_length for more flexibility and control.

        Nr5   rN   r   s     r7   writezPayload.write          content_lengthc                 B   K   | j                  |       d{    y7 w)a  
        Write payload with a specific content length constraint.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing
            content_length: Maximum number of bytes to write (None for unlimited)

        This method allows writing payload content with a specific length constraint,
        which is particularly useful for HTTP responses with Content-Length header.

        Note:
            This is the base implementation that provides backwards compatibility
            for subclasses that don't override this method. Specific payload types
            should override this method to implement proper length-constrained writing.

        N)r   rN   r   r   s      r7   write_with_lengthzPayload.write_with_length  s     * jj   s   c                 l   K   | j                   xs |}| j                  ||      j                  |      S w)z
        Return bytes representation of the value.

        This is a convenience method that calls decode() and encodes the result
        to bytes using the specified encoding.
        )ru   r   r   )rN   rq   r   actual_encodings       r7   as_byteszPayload.as_bytes4  s2      ..4H{{?F3::?KKs   24c                      y)a  
        Async safe synchronous close operations for backwards compatibility.

        This method exists only for backwards compatibility with code that
        needs to clean up payloads synchronously. In the future, we will
        drop this method and only support the async close() method.

        WARNING: This method must be safe to call from within the event loop
        without blocking. Subclasses should not perform any blocking I/O here.

        WARNING: This method must be called from within an event loop for
        certain payload types (e.g., IOBasePayload). Calling it outside an
        event loop may raise RuntimeError.
        Nr5   rZ   s    r7   _closezPayload._close?  r   r6   c                 ,   K   | j                          yw)a\  
        Close the payload if it holds any resources.

        IMPORTANT: This method must not await anything that might not finish
        immediately, as it may be called during cleanup/cancellation. Schedule
        any long-running operations without awaiting them.

        In the future, this will be the only close method supported.
        Nr   rZ   s    r7   closezPayload.closeQ  s      	   )Tr   r   strictrd   )(r1   r2   r3   ri   str__annotations__rj   r   intrk   boolrl   r   r	   r   r   r
   r   r   r   rO   propertyr   rp   rn   bytesr   rq   ro   r   r   r   r   r   r   r   r   r   r   r   r5   r6   r7   r"   r"      sz   !;3;E8C=ItJ 4<"&"&** ,S#XsCx0IIJ
* Cy01* 3-* 3-* * 
*> hsm   (3-      
 
 
 (3-   0c 0 0 $   4   "	



 

 	


 

 


 s c    "6 4  *!*!<DSM!	!.	Ls 	Lc 	LQV 	L$
r6   c                        e Zd ZU eed<   dZdeeeef   de	de	ddf fdZ
dd	ed
edefdZdd	ed
edefdZdeddfdZdedee   ddfdZ xZS )r#   rx   Trm   r>   r?   r@   Nc                 d   d|vrd|d<   t        |   |g|i | t        |t              r|j                  | _        n>t        |t        t        f      rt        |      | _        nt        dt        |            | j
                  t        kD  r d| i}t        j                  dt        fi | y y )Nro   rh   z%value argument must be byte-ish, not sourcez}Sending a large body directly with raw bytes might lock the event loop. You should probably pass an io.BytesIO object instead)superrO   r]   
memoryviewnbytesrj   r   	bytearraylen	TypeErrorrG   r,   warningswarnResourceWarningrN   rm   r>   r?   	__class__s       r7   rO   zBytesPayload.__init__c  s     '%?F>"000eZ(DJy12UDJCDK?STT::,,%FMM,  	
  -r6   rq   r   c                 :    | j                   j                  ||      S rB   )rx   r   r   s      r7   r   zBytesPayload.decode|  s    {{!!(F33r6   c                 "   K   | j                   S w)z
        Return bytes representation of the value.

        This method returns the raw bytes content of the payload.
        It is equivalent to accessing the _value attribute directly.
        )rx   r   s      r7   r   zBytesPayload.as_bytes  s      {{s   r   c                 V   K   |j                  | j                         d{    y7 w)a  
        Write the entire bytes payload to the writer stream.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing

        This method writes the entire bytes content without any length constraint.

        Note:
            For new implementations that need length control, use write_with_length().
            This method is maintained for backwards compatibility and is equivalent
            to write_with_length(writer, None).

        Nr   rx   r   s     r7   r   zBytesPayload.write  s      ll4;;'''s   )')r   c                    K   |'|j                  | j                  d|        d{    y|j                  | j                         d{    y7 )7 w)a  
        Write bytes payload with a specific content length constraint.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing
            content_length: Maximum number of bytes to write (None for unlimited)

        This method writes either the entire byte sequence or a slice of it
        up to the specified content_length. For BytesPayload, this operation
        is performed efficiently using array slicing.

        Nr   r   s      r7   r   zBytesPayload.write_with_length  sJ      %,,t{{?N;<<<,,t{{+++ =+s!   $AA#A
AAAr   )r1   r2   r3   r   r   rl   r   r   r   r	   rO   r   r   r   r   r   r   r   r   __classcell__r   s   @r7   r#   r#   ^  s    MJ5)Z78ADPS	24s 4c 4 4s c QV ("6 (4 (",*,<DSM,	,r6   r#   c                   L     e Zd Zddddededee   dee   deddf fd	Z xZS )
r$   Nrq   ro   rm   r>   rq   ro   r?   r@   c                    |/|d}d}n1t        |      }|j                  j                  dd      }n	|d|z  }|}t        |   |j                  |      g|||d| y )Nr   text/plain; charset=utf-8charsettext/plain; charset=%sr   )r   
parametersrC   r   rO   r   )	rN   rm   rq   ro   r>   r?   real_encodingmimetyper   s	           r7   rO   zStringPayload.__init__  s     # ':),7 ( 3 3 7 7	7 K#7(B$MLL'	
 		
"%	

 	
r6   )r1   r2   r3   r   r	   r   rO   r   r   s   @r7   r$   r$     sW    
 #'&*

 
 3-	

 sm
 
 

 
r6   r$   c                   6     e Zd Zdee   dededdf fdZ xZS )r)   rm   r>   r?   r@   Nc                 H    t        |   |j                         g|i | y rB   )r   rO   readr   s       r7   rO   zStringIOPayload.__init__  s     777r6   )r1   r2   r3   r   r   r	   rO   r   r   s   @r7   r)   r)     s-    8bg 8c 8S 8T 8 8r6   r)   c                   h    e Zd ZU ej                  ed<   dZee   ed<   	 dde	e
   dede
de
ddf
 fd	Zdd
Zdee   deee   ef   fdZdee   defdZedee   fd       ZdeddfdZdedee   ddfdZdee   dedee   defdZddZddZddededefdZdefdZddededefdZ xZS ) r%   rx   N_start_positionrm   dispositionr>   r?   r@   c                     d|vrt        |      |d<   t        |   |g|i | | j                  >|;t        j
                  | j                  vr| j                  || j                         y y y y )Nrp   )rp   )r   r   rO   rv   r   r   rn   r   )rN   rm   r   r>   r?   r   s        r7   rO   zIOBasePayload.__init__  sy     V#!/!6F:000>>%+*A''t||;,,[4>>,R < +B%r6   c                     | j                   !	 | j                  j                         | _         y| j                  j                  | j                          y# t        $ r
 d| _        Y yw xY w)z:Set or restore the start position of the file-like object.NT)r   rx   tellOSErrorrk   seekrZ   s    r7   _set_or_restore_start_positionz,IOBasePayload._set_or_restore_start_position  s`    '&'+{{'7'7'9$ --.  &!%&s   A A'&A'remaining_content_lenc           	          | j                          | j                  }|| j                  j                  t	        t
        |xs t
        |xs t
                    fS )a  
        Read the file-like object and return both its total size and the first chunk.

        Args:
            remaining_content_len: Optional limit on how many bytes to read in this operation.
                If None, READ_SIZE will be used as the default chunk size.

        Returns:
            A tuple containing:
            - The total size of the remaining unread content (None if size cannot be determined)
            - The first chunk of bytes read from the file object

        This method is optimized to perform both size calculation and initial read
        in a single operation, which is executed in a single executor job to minimize
        context switches and file operations when streaming content.

        )r   r   rx   r   minr-   )rN   r   r   s      r7   _read_and_available_lenz%IOBasePayload._read_and_available_len  sN    ( 	++-yyT[[%%	4,9.C.PyQ
 
 	
r6   c                 H    | j                   j                  |xs t              S )a  
        Read a chunk of data from the file-like object.

        Args:
            remaining_content_len: Optional maximum number of bytes to read.
                If None, READ_SIZE will be used as the default chunk size.

        Returns:
            A chunk of bytes read from the file object, respecting the
            remaining_content_len limit if specified.

        This method is used for subsequent reads during streaming after
        the initial _read_and_available_len call has been made.

        )rx   r   r-   )rN   r   s     r7   _readzIOBasePayload._read  s      {{ 5 BCCr6   c                     	 t        j                  | j                  j                               j                  | j                  j                         z
  S # t        t        f$ r Y yw xY w)z
        Size of the payload in bytes.

        Returns the number of bytes remaining to be read from the file.
        Returns None if the size cannot be determined (e.g., for unseekable streams).
        N)osfstatrx   filenost_sizer   AttributeErrorr   rZ   s    r7   r   zIOBasePayload.size  sR    	88DKK..0199DKK<L<L<NNN( 		s   AA A&%A&r   c                 D   K   | j                  |d       d{    y7 w)a0  
        Write the entire file-like payload to the writer stream.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing

        This method writes the entire file content without any length constraint.
        It delegates to write_with_length() with no length limit for implementation
        consistency.

        Note:
            For new implementations that need length control, use write_with_length() directly.
            This method is maintained for backwards compatibility with existing code.

        Nr   r   s     r7   r   zIOBasePayload.write'  s       $$VT222     r   c                   K   t        j                         }d}|}|j                  d| j                  |       d{   \  }}|rt	        |      }||j                  |       d{    n!|j                  |d|        d{    ||z  }||z  }| j                  |||      ry|j                  d| j                  |t        t        |      nt               d{   }|ryy7 7 7 f7 w)a  
        Write file-like payload with a specific content length constraint.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing
            content_length: Maximum number of bytes to write (None for unlimited)

        This method implements optimized streaming of file content with length constraints:

        1. File reading is performed in a thread pool to avoid blocking the event loop
        2. Content is read and written in chunks to maintain memory efficiency
        3. Writing stops when either:
           - All available file content has been written (when size is known)
           - The specified content_length has been reached
        4. File resources are properly closed even if the operation is cancelled

        The implementation carefully handles both known-size and unknown-size payloads,
        as well as constrained and unconstrained content lengths.

        r   N)
asyncioget_running_looprun_in_executorr   r   r   _should_stop_writingr   r   r-   )	rN   r   r   looptotal_written_lenr   available_lenchunk	chunk_lens	            r7   r   zIOBasePayload.write_with_length9  s    . '') . &*%9%9$..0E&
  
u E
I %,ll5)))ll5)?*?#@AAA%2%* ((02G  ..

 -8 	#89" E' 	 
 *AsL   9C.C&*C.&C('C.C*AC.C,C.$C.(C.*C.,C.r   r   c                 2    |duxr ||k\  xs |duxr |dk  S )a3  
        Determine if we should stop writing data.

        Args:
            available_len: Known size of the payload if available (None if unknown)
            total_written_len: Number of bytes already written
            remaining_content_len: Remaining bytes to be written for content-length limited responses

        Returns:
            True if we should stop writing data, based on either:
            - Having written all available data (when size is known)
            - Having written all requested content (when content-length is specified)

        Nr   r5   )rN   r   r   r   s       r7   r   z"IOBasePayload._should_stop_writingv  s4    ( T)P.?=.P 
!-L2G12L	
r6   c                    | j                   ryd| _         t        j                         }|j                  d| j                  j
                        }t        j                  |       |j                  t        j                         y)aL  
        Async safe synchronous close operations for backwards compatibility.

        This method exists only for backwards
        compatibility. Use the async close() method instead.

        WARNING: This method MUST be called from within an event loop.
        Calling it outside an event loop will raise RuntimeError.
        NT)
rk   r   r   r   rx   r   r.   addadd_done_callbackremove)rN   r   close_futures      r7   r   zIOBasePayload._close  sc     >>'')++D$++2C2CD 	<(&&~'<'<=r6   c                 ,   K   | j                          yw)a  
        Close the payload if it holds any resources.

        IMPORTANT: This method must not await anything that might not finish
        immediately, as it may be called during cleanup/cancellation. Schedule
        any long-running operations without awaiting them.
        Nr   rZ   s    r7   r   zIOBasePayload.close  s      	r   rq   r   c                 B    | j                         j                  ||      S z
        Return string representation of the value.

        WARNING: This method does blocking I/O and should not be called in the event loop.
        )	_read_allr   r   s      r7   r   zIOBasePayload.decode  s     ~~&&x88r6   c                 t    | j                          dj                  | j                  j                               S )zARead the entire file-like object and return its content as bytes.r6   )r   r   rx   	readlinesrZ   s    r7   r	  zIOBasePayload._read_all  s*    ++-xx--/00r6   c                 ~   K   t        j                         }|j                  d| j                         d{   S 7 w)a!  
        Return bytes representation of the value.

        This method reads the entire file content and returns it as bytes.
        It is equivalent to reading the file-like object directly.
        The file reading is performed in an executor to avoid blocking the event loop.
        N)r   r   r   r	  )rN   rq   r   r   s       r7   r   zIOBasePayload.as_bytes  s3      '')))$????s   4=;=)
attachmentrd   r   )r1   r2   r3   ioIOBaser   r   r   r   r   r	   r   rO   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r   r   r   s   @r7   r%   r%     st   II%)OXc]) 2>
SW
S+.
SFI
SUX
S	
S/
%-c]
	x}e#	$
4D8C= DU D$ 
hsm 
 
3"6 34 3$;*;<DSM;	;z
}
 
  (}	

 

0>,9s 9c 9 915 1	@s 	@c 	@QV 	@r6   r%   c                        e Zd ZU ej                  ed<   ddddededee	   dee	   ded	df fd
Z
dee   d	eee   ef   fdZdee   d	efdZdde	de	d	e	fdZdde	de	d	efdZ xZS )r(   rx   Nr   rm   r>   rq   ro   r?   r@   c                    |/|d}d}n/t        |      }|j                  j                  dd      }n|d|z  }t        |   |g|||d| y )Nr   r   r   r   ro   rq   )r   r   rC   r   rO   )rN   rm   rq   ro   r>   r?   r   r   s          r7   rO   zTextIOPayload.__init__  s|     #":),7#..229gF#7(B	
 		
%	

 	
r6   r   c                 "   | j                          | j                  }| j                  j                  t	        t
        |xs t
        |xs t
                    }|| j                  r|j                  | j                        fS |j                         fS )a  
        Read the text file-like object and return both its total size and the first chunk.

        Args:
            remaining_content_len: Optional limit on how many bytes to read in this operation.
                If None, READ_SIZE will be used as the default chunk size.

        Returns:
            A tuple containing:
            - The total size of the remaining unread content (None if size cannot be determined)
            - The first chunk of bytes read from the file object, encoded using the payload's encoding

        This method is optimized to perform both size calculation and initial read
        in a single operation, which is executed in a single executor job to minimize
        context switches and file operations when streaming content.

        Note:
            TextIOPayload handles encoding of the text content before writing it
            to the stream. If no encoding is specified, UTF-8 is used as the default.

        )r   r   rx   r   r   r-   ru   r   )rN   r   r   r   s       r7   r   z%TextIOPayload._read_and_available_len  sr    0 	++-yy  	4,9.C.PyQ
 T^^U\\$..1WWWWr6   c                     | j                   j                  |xs t              }| j                  r|j	                  | j                        S |j	                         S )a  
        Read a chunk of data from the text file-like object.

        Args:
            remaining_content_len: Optional maximum number of bytes to read.
                If None, READ_SIZE will be used as the default chunk size.

        Returns:
            A chunk of bytes read from the file object and encoded using the payload's
            encoding. The data is automatically converted from text to bytes.

        This method is used for subsequent reads during streaming after
        the initial _read_and_available_len call has been made. It properly
        handles text encoding, converting the text content to bytes using
        the specified encoding (or UTF-8 if none was provided).

        )rx   r   r-   ru   r   )rN   r   r   s      r7   r   zTextIOPayload._read  sB    $   !6!C)D/3~~u||DNN+Q5<<>Qr6   r   c                 V    | j                          | j                  j                         S r  r   rx   r   r   s      r7   r   zTextIOPayload.decode  s#     	++-{{!!r6   c                     K   t        j                         } j                  xs |dt        f fd}|j	                  d|       d{   S 7 w)a%  
        Return bytes representation of the value.

        This method reads the entire text file content and returns it as bytes.
        It encodes the text content using the specified encoding.
        The file reading is performed in an executor to avoid blocking the event loop.
        r@   c                  x    j                          j                  j                         j                         S rB   )r   rx   r   r   )r   r   rN   s   r7   _read_and_encodez0TextIOPayload.as_bytes.<locals>._read_and_encode2  s/    //1;;##%,,_fEEr6   N)r   r   ru   r   r   )rN   rq   r   r   r  r   s   ` `  @r7   r   zTextIOPayload.as_bytes%  sQ      '') ..4H	F% 	F
 ))$0@AAAAs   AAAAr   )r1   r2   r3   r  
TextIOBaser   r   r	   r   r   rO   r   r   r   r   r   r   r   r   r   s   @r7   r(   r(     s    MM #'&*

 
 3-	

 sm
 
 

8X%-c]X	x}e#	$X>R8C= RU R*"s "c " "Bs Bc BQV Br6   r(   c                        e Zd ZU ej                  ed<   eed<   dZdej                  dededdf fd	Z	e
defd
       ZddededefdZdeddfdZdedee   ddfdZddededefdZddZ xZS )r&   rx   rj   Trm   r>   r?   r@   Nc                     t        |   |g|i | t        | j                  j	                               | j                  j                         z
  | _        y rB   )r   rO   r   rx   	getbufferr   rj   r   s       r7   rO   zBytesIOPayload.__init__?  sE    000..01DKK4D4D4FF
r6   c                     | j                   S )zSize of the payload in bytes.

        Returns the number of bytes in the BytesIO buffer that will be transmitted.
        This is calculated once during initialization for efficiency.
        r   rZ   s    r7   r   zBytesIOPayload.sizeD  s     zzr6   rq   r   c                 v    | j                          | j                  j                         j                  ||      S rB   r   rx   r   r   r   s      r7   r   zBytesIOPayload.decodeM  .    ++-{{!((6::r6   r   c                 B   K   | j                  |d        d {   S 7 wrB   r   r   s     r7   r   zBytesIOPayload.writeQ  s     ++FD9999s   r   c                   K   | j                          d}|}| j                  j                  t              x}r|dkD  rt	        j
                  d       d{    ||j                  |       d{    n0|j                  |d|        d{    |t        |      z  }|dk  ry|dz  }| j                  j                  t              x}ryy7 y7 `7 Ew)a:  
        Write BytesIO payload with a specific content length constraint.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing
            content_length: Maximum number of bytes to write (None for unlimited)

        This implementation is specifically optimized for BytesIO objects:

        1. Reads content in chunks to maintain memory efficiency
        2. Yields control back to the event loop periodically to prevent blocking
           when dealing with large BytesIO objects
        3. Respects content_length constraints when specified
        4. Properly cleans up by closing the BytesIO object when done or on error

        The periodic yielding to the event loop is important for maintaining
        responsiveness when processing large in-memory buffers.

        r   Nr   )r   rx   r   r-   r   sleepr   r   )rN   r   r   
loop_countremaining_bytesr   s         r7   r   z BytesIOPayload.write_with_lengthT  s     , 	++-
({{''	22e2A~
 mmA&&&&ll5)))ll5)9/#:;;;3u:-"a'!OJ {{''	22e2 ');s<   ACCC0C1CC>CCCCc                 ^   K   | j                          | j                  j                         S w)z
        Return bytes representation of the value.

        This method reads the entire BytesIO content and returns it as bytes.
        It is equivalent to accessing the _value attribute directly.
        r  r   s      r7   r   zBytesIOPayload.as_bytes}  s'      	++-{{!!s   +-c                    K   yw)z
        Close the BytesIO payload.

        This does nothing since BytesIO is in-memory and does not require explicit closing.
        Nr5   rZ   s    r7   r   zBytesIOPayload.close  r   r   r   rd   )r1   r2   r3   r  BytesIOr   r   rl   r	   rO   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r7   r&   r&   :  s    JJJJGbjj G G G G
 c  ;s ;c ; ;:"6 :4 :'*'<DSM'	'R"s "c "QV "r6   r&   c                   B    e Zd ZU ej                  ed<   ddededefdZy)r'   rx   rq   r   r@   c                 v    | j                          | j                  j                         j                  ||      S rB   r   r   s      r7   r   zBufferedReaderPayload.decode  r!  r6   Nr   )r1   r2   r3   r  BufferedIOBaser   r   r   r5   r6   r7   r'   r'     s(    ;s ;c ; ;r6   r'   c                   X     e Zd Zddej                  fdedededededed	d
f fdZ xZ	S )r*   r   zapplication/jsonrm   rq   ro   dumpsr>   r?   r@   Nc                 \    t        |    ||      j                  |      g|||d| y )Nr  )r   rO   r   )rN   rm   rq   ro   r.  r>   r?   r   s          r7   rO   zJsonPayload.__init__  sC     	%L)	
 		
%	

 	
r6   )
r1   r2   r3   jsonr.  r	   r   r   rO   r   r   s   @r7   r*   r*     s`      .!ZZ

 
 	

 
 
 
 

 
r6   r*   )AsyncIterableAsyncIteratorc                        e Zd ZU dZee   ed<   eed<   dZee	e
      ed<   dZdededed	df fd
Zded	dfdZdedee   d	dfdZddeded	efdZddeded	e
fdZ xZS )r+   N_iterrx   _cached_chunksTrm   r>   r?   r@   c                     t        |t              s#t        dj                  t	        |                  d|vrd|d<   t        |   |g|i | |j                         | _        y )NzMvalue argument must support collections.abc.AsyncIterable interface, got {!r}ro   rh   )	r]   r1  r   formatrG   r   rO   	__aiter__r4  r   s       r7   rO   zAsyncIterablePayload.__init__  sf    %/!6$u+.  '%?F>"000__&
r6   r   c                 D   K   | j                  |d       d{    y7 w)a  
        Write the entire async iterable payload to the writer stream.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing

        This method iterates through the async iterable and writes each chunk
        to the writer without any length constraint.

        Note:
            For new implementations that need length control, use write_with_length() directly.
            This method is maintained for backwards compatibility with existing code.

        Nr   r   s     r7   r   zAsyncIterablePayload.write  s      $$VT222r   r   c                   K   | j                   a|}| j                   D ]O  }||j                  |       d{    |dkD  r+|j                  |d|        d{    |t        |      z  }O y y| j                  y|}	 	 t        j
                  dk\  rt        | j                         d{   }n"| j                  j                          d{   }||j                  |       d{    n/|dkD  r*|j                  |d|        d{    |t        |      z  }7 7 7 w7 V7 =7 # t        $ r d| _        d| _	        Y yw xY ww)ay  
        Write async iterable payload with a specific content length constraint.

        Args:
            writer: An AbstractStreamWriter instance that handles the actual writing
            content_length: Maximum number of bytes to write (None for unlimited)

        This implementation handles streaming of async iterable content with length constraints:

        1. If cached chunks are available, writes from them
        2. Otherwise iterates through the async iterable one chunk at a time
        3. Respects content_length constraints when specified
        4. Does NOT generate cache - that's done by as_bytes()

        Nr   T)rs   
   )
r5  r   r   r4  rz   r{   anext	__anext__StopAsyncIterationrk   )rN   r   r   r&  r   s        r7   r   z&AsyncIterablePayload.write_with_length  s\    & *,O,, "* ,,u---$q( ,,u-=o'>???#s5z1O  :: )	"##w."'

"33E"&**"6"6"88E"* ,,u---$q( ,,u-=o'>???#s5z1O ! .?  48- @ " 	"DJ!DN	"s   4E	D !E	D"&E	 ,D, ,D$-"D, D&D, *D(+!D, D*D,  E	"E	$D, &D, (D, *D, ,EE	EE	rq   r   c                     | j                   +dj                  | j                         j                  ||      S t        d      )zFDecode the payload content as a string if cached chunks are available.r6   z=Unable to decode - content not cached. Call as_bytes() first.)r5  r   r   r   r   s      r7   r   zAsyncIterablePayload.decode  s<    *88D//077&IIWXXr6   c                   K   | j                   dj                  | j                         S | j                  yg }| j                  2 3 d{   }|j                  |       7 6 d| _        || _         dj                  |      S w)z
        Return bytes representation of the value.

        This method reads the entire async iterable content and returns it as bytes.
        It generates and caches the chunks for future reuse.
        Nr6   )r5  r   r4  ra   )rN   rq   r   chunksr   s        r7   r   zAsyncIterablePayload.as_bytes!  s      *88D//00 :: !:: 	! 	!%MM% 	!: 
$ xxs*   ABA"	A 
A"B A"" Br   )r1   r2   r3   r4  r   _AsyncIteratorr   _AsyncIterabler5  r   r   rl   r	   rO   r   r   r   r   r   r   r   r   r   s   @r7   r+   r+     s    &*E8N#*,0NHT%[)0J'n 'S 'C 'D '3"6 34 3"9"*9"<DSM9"	9"vYs Yc Y Y s  c  QV  r6   r+   c                   0     e Zd Zdedededdf fdZ xZS )StreamReaderPayloadrm   r>   r?   r@   Nc                 H    t        |   |j                         g|i | y rB   )r   rO   iter_anyr   s       r7   rO   zStreamReaderPayload.__init__>  s!    );D;F;r6   )r1   r2   r3   r   r	   rO   r   r   s   @r7   rE  rE  =  s)    <l <3 <# <$ < <r6   rE  )[r   enumr  r0  r|   r   rz   r   abcr   r   collections.abcr   	itertoolsr   typingr   r   r	   r
   r   r   r   r   r   r   r   r   	multidictr   r   r   r   helpersr   r   r   r   r   streamsr   typedefsr   r   __all__r,   r   r   r-   setr.   Future	Exceptionr0   r   Enumr9   r    r:   rK   r!   rf   _PayloadRegistryItemrS   r"   r#   r$   r)   r%   r(   r&   r'   r*   r1  r2  r   rB  rC  r+   rE  r   rJ   r   r   StringIOr  r)  BufferedReaderBufferedRandomr  r<   r5   r6   r7   <module>rZ     s     	   	 
  # $     "  %  " /  $) eCj (	5: ,/EGNN4() 1K) KC 7c 7# 7 7 7
 <A<<:)_:$':38:	:  9o[#-. 4= 4=nDc DNM,7 M,`
L 
>8m 8
s@G s@loBM oBdR] Rj;M ;
, 
( 3"5)N"5)N<"N"NB 7 B J<. <
 #$    ,	:(F G   - -   /2;; 7   - 7   ."** 5   /"2C2CREVEV1W X   - 3   -| <   .U^^  Tr6   