o w[ed@s&dZddlZddlZddlZddlZddlZeedred7ZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd l mZdd lmZd ZdedddZdedddZeedrpd edddZd edddZGddde jZGdddee jZGdddZGdddZdS)!) StreamReader StreamWriterStreamReaderProtocolopen_connection start_serverNAF_UNIX)open_unix_connectionstart_unix_server) coroutines)events) exceptions)format_helpers) protocols)logger)sleepi)limitc s`t}t||d}t||d|jfdd||fi|IdH\}}t|||}||fS)aA wrapper for create_connection() returning a (reader, writer) pair. The reader returned is a StreamReader instance; the writer is a StreamWriter instance. The arguments are all the usual arguments to create_connection() except protocol_factory; most common are positional host and port, with various optional keyword arguments following. Additional optional keyword arguments are loop (to set the event loop instance to use) and limit (to set the buffer limit passed to the StreamReader). (If you want to customize the StreamReader and/or StreamReaderProtocol classes, just copy the code -- there's really nothing special here except some convenience.) rlooprcSNrprotocolr&/usr/lib/python3.10/asyncio/streams.py1z!open_connection..N)r get_running_looprrcreate_connectionr) hostportrkwdsrreader transport_writerrrrrs  rcs6tfdd}j|||fi|IdHS)aStart a socket server, call back for each client connected. The first parameter, `client_connected_cb`, takes two parameters: client_reader, client_writer. client_reader is a StreamReader object, while client_writer is a StreamWriter object. This parameter can either be a plain callback function or a coroutine; if it is a coroutine, it will be automatically converted into a Task. The rest of the arguments are all the usual arguments to loop.create_server() except protocol_factory; most common are positional host and port, with various optional keyword arguments following. The return value is the same as loop.create_server(). Additional optional keyword arguments are loop (to set the event loop instance to use) and limit (to set the buffer limit passed to the StreamReader). The return value is the same as loop.create_server(), i.e. a Server object which can be used to stop the service. ctd}t|d}|SNrrrrr#rclient_connected_cbrrrrfactoryO zstart_server..factoryN)r r create_server)r,r r!rr"r-rr+rr6srcs^t}t||d}t||d|jfdd|fi|IdH\}}t|||}||fS)z@Similar to `open_connection` but works with UNIX Domain Sockets.rrcrrrrrrrrcrz&open_unix_connection..N)r rrrcreate_unix_connectionr)pathrr"rr#r$r%r&rrrr[s   rcs4tfdd}j||fi|IdHS)z=Similar to `start_server` but works with UNIX Domain Sockets.cr'r(r)r*r+rrr-lr.z"start_unix_server..factoryN)r rcreate_unix_server)r,r1rr"r-rr+rr gsr c@sBeZdZdZdddZddZddZd d Zd d Zd dZ dS)FlowControlMixina)Reusable flow control logic for StreamWriter.drain(). This implements the protocol methods pause_writing(), resume_writing() and connection_lost(). If the subclass overrides these it must call the super methods. StreamWriter.drain() must wait for _drain_helper() coroutine. NcCs8|dur tjdd|_n||_d|_t|_d|_dS)N) stacklevelF)r _get_event_loop_loop_paused collectionsdeque_drain_waiters_connection_lost)selfrrrr__init__s   zFlowControlMixin.__init__cCs.|jrJd|_|jrtd|dSdS)NTz%r pauses writing)r8r7 get_debugrdebugr=rrr pause_writings  zFlowControlMixin.pause_writingcCsH|jsJd|_|jrtd||jD] }|s!|dqdS)NFz%r resumes writing)r8r7r?rr@r;done set_resultr=waiterrrrresume_writings     zFlowControlMixin.resume_writingcCsFd|_|jsdS|jD]}|s |dur|dq ||q dSNT)r<r8r;rCrD set_exceptionr=excrFrrrconnection_losts   z FlowControlMixin.connection_lostc s\|jrtd|js dS|j}|j|z|IdHW|j|dS|j|w)NzConnection lost)r<ConnectionResetErrorr8r7 create_futurer;appendremoverErrr _drain_helpers   zFlowControlMixin._drain_helpercCstr)NotImplementedErrorr=streamrrr_get_close_waiterz"FlowControlMixin._get_close_waiterr) __name__ __module__ __qualname____doc__r>rBrGrLrQrUrrrrr3us    r3csfeZdZdZdZdfdd ZeddZddZfd d Z d d Z d dZ ddZ ddZ ZS)ra=Helper class to adapt between Protocol and StreamReader. (This is a helper class instead of making StreamReader itself a Protocol subclass, because the StreamReader has other potential uses, and to prevent the user of the StreamReader to accidentally call inappropriate methods of the protocol.) Ncsttj|d|durt||_|j|_nd|_|dur ||_d|_d|_d|_ d|_ ||_ d|_ |j |_dS)NrF)superr>weakrefref_stream_reader_wr_source_traceback_strong_reader_reject_connection_stream_writer_task _transport_client_connected_cb _over_sslr7rN_closed)r= stream_readerr,r __class__rrr>s  zStreamReaderProtocol.__init__cCs|jdurdS|Sr)r^rArrr_stream_readers z#StreamReaderProtocol._stream_readercCs|jrddi}|jr|j|d<|j||dS||_|j}|dur*|||ddu|_ |j durXt ||||j|_ | ||j }t |rS|j||_d|_dSdS)NmessagezpAn open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.source_traceback sslcontext)rar_r7call_exception_handlerabortrdrk set_transportget_extra_inforfrerrbr iscoroutine create_taskrcr`)r=r$contextr#resrrrconnection_mades2      z$StreamReaderProtocol.connection_madecs~|j}|dur|dur|n|||js+|dur%|jdn|j|t|d|_d|_ d|_ d|_ dSr) rkfeed_eofrIrgrCrDr[rLr^rbrcrd)r=rKr#rirrrLs      z$StreamReaderProtocol.connection_lostcCs |j}|dur||dSdSr)rk feed_data)r=datar#rrr data_receivedsz"StreamReaderProtocol.data_receivedcCs$|j}|dur ||jrdSdS)NFT)rkrxrf)r=r#rrr eof_received s z!StreamReaderProtocol.eof_receivedcC|jSr)rgrSrrrrUz&StreamReaderProtocol._get_close_waitercCsDz|j}Wn tyYdSw|r|s |dSdSdSr)rgAttributeErrorrC cancelled exception)r=closedrrr__del__s   zStreamReaderProtocol.__del__NN)rWrXrYrZr_r>propertyrkrwrLr{r|rUr __classcell__rrrirrs   rc@sveZdZdZddZddZeddZdd Zd d Z d d Z ddZ ddZ ddZ ddZdddZddZdS)ra'Wraps a Transport. This exposes write(), writelines(), [can_]write_eof(), get_extra_info() and close(). It adds drain() which returns an optional Future on which you can wait for flow control. It also adds a transport property which references the Transport directly. cCsJ||_||_|dust|tsJ||_||_|j|_|jddSr) rd _protocol isinstancer_readerr7rN _complete_futrD)r=r$rr#rrrrr>0s zStreamWriter.__init__cCs@|jjd|jg}|jdur|d|jdd|S)N transport=zreader=<{}> )rjrWrdrrOformatjoinr=inforrr__repr__:s zStreamWriter.__repr__cCr}rrdrArrrr$@szStreamWriter.transportcC|j|dSr)rdwriter=rzrrrrDzStreamWriter.writecCrr)rd writelinesrrrrrGrzStreamWriter.writelinescC |jSr)rd write_eofrArrrrJ zStreamWriter.write_eofcCrr)rd can_write_eofrArrrrMrzStreamWriter.can_write_eofcCrr)rdcloserArrrrPrzStreamWriter.closecCrr)rd is_closingrArrrrSrzStreamWriter.is_closingcs|j|IdHdSr)rrUrArrr wait_closedVszStreamWriter.wait_closedNcCs|j||Sr)rdrr)r=namedefaultrrrrrYszStreamWriter.get_extra_infocsN|jdur|j}|dur||jrtdIdH|jIdHdS)zyFlush the write buffer. The intended use is to write w.write(data) await w.drain() Nr)rrrdrrrrQ)r=rKrrrdrain\s    zStreamWriter.drainr)rWrXrYrZr>rrr$rrrrrrrrrrrrrrr&s     rc@seZdZdZedfddZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZd&ddZd'ddZd d!Zd"d#Zd$d%ZdS)(rNcCsz|dkrtd||_|durt|_n||_t|_d|_d|_d|_ d|_ d|_ |j r;t td|_dSdS)NrzLimit cannot be <= 0Fr ) ValueError_limitr r6r7 bytearray_buffer_eof_waiter _exceptionrdr8r?r extract_stacksys _getframer_)r=rrrrrr>zs"   zStreamReader.__init__cCsdg}|jr|t|jd|jr|d|jtkr'|d|j|jr3|d|j|jr?|d|j|jrK|d|j|j rS|dd d |S) Nrz byteseofzlimit=zwaiter=z exception=rpausedrr) rrOlenrr_DEFAULT_LIMITrrrdr8rrrrrrrs    zStreamReader.__repr__cCr}r)rrArrrrr~zStreamReader.exceptioncCs8||_|j}|durd|_|s||dSdSdSr)rrrrIrJrrrrIszStreamReader.set_exceptioncCs2|j}|durd|_|s|ddSdSdS)z1Wakeup read*() functions waiting for data or EOF.N)rrrDrErrr_wakeup_waiterszStreamReader._wakeup_waitercCs|jdus Jd||_dS)NzTransport already setr)r=r$rrrrqs zStreamReader.set_transportcCs2|jrt|j|jkrd|_|jdSdSdS)NF)r8rrrrdresume_readingrArrr_maybe_resume_transportsz$StreamReader._maybe_resume_transportcCsd|_|dSrH)rrrArrrrxs zStreamReader.feed_eofcCs|jo|j S)z=Return True if the buffer is empty and 'feed_eof' was called.)rrrArrrat_eofszStreamReader.at_eofcCs|jrJd|s dS|j|||jdurA|jsCt|jd|jkrEz|jWn t y;d|_YdSwd|_dSdSdSdS)Nzfeed_data after feed_eofT) rrextendrrdr8rr pause_readingrRrrrrrys"     zStreamReader.feed_datacsl|jdur t|d|jrJd|jrd|_|j|j|_z |jIdHWd|_dSd|_w)zpWait until feed_data() or feed_eof() is called. If stream was paused, automatically resume it. NzF() called while another coroutine is already waiting for incoming dataz_wait_for_data after EOFF)r RuntimeErrorrr8rdrr7rN)r= func_namerrr_wait_for_datas   zStreamReader._wait_for_datac sd}t|}z ||IdH}W|Stjy(}z |jWYd}~Sd}~wtjyV}z"|j||jrB|jd|j|=n|j | t |j dd}~ww)aRead chunk of data from the stream until newline (b' ') is found. On success, return chunk that ends with newline. If only partial line can be read due to EOF, return incomplete line without terminating newline. When EOF was reached while no bytes read, empty bytes object is returned. If limit is reached, ValueError will be raised. In that case, if newline was found, complete line including newline will be removed from internal buffer. Else, internal buffer will be cleared. Limit is compared against part of the line without newline. If stream was paused, this function will automatically resume it if needed.  Nr) r readuntilr IncompleteReadErrorpartialLimitOverrunErrorr startswithconsumedclearrrargs)r=sepseplenlineerrrreadlines"  zStreamReader.readlinercst|}|dkr td|jdur|jd} t|j}|||kr@|j||}|dkr/n-|d|}||jkr@td||jrSt |j}|j t |d| dIdHq||jkrgtd ||jd||}|jd||=| t |S) aVRead data from the stream until ``separator`` is found. On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the separator at the end. Configured stream limit is used to check result. Limit sets the maximal length of data that can be returned, not counting the separator. If an EOF occurs and the complete separator is still not found, an IncompleteReadError exception will be raised, and the internal buffer will be reset. The IncompleteReadError.partial attribute may contain the separator partially. If the data cannot be read because of over limit, a LimitOverrunError exception will be raised, and the data will be left in the internal buffer, so it can be read again. rz,Separator should be at least one-byte stringNTr z2Separator is not found, and chunk exceed the limitrz2Separator is found, but chunk is longer than limit)rrrrfindrr rrbytesrrrr)r= separatorroffsetbuflenisepchunkrrrrsB         zStreamReader.readuntilrcs|jdur |j|dkrdS|dkr-g} ||jIdH}|s"n||qd|S|js;|js;|dIdHt|jd|}|jd|=| |S)aRead up to `n` bytes from the stream. If `n` is not provided or set to -1, read until EOF, then return all read bytes. If EOF was received and the internal buffer is empty, return an empty bytes object. If `n` is 0, return an empty bytes object immediately. If `n` is positive, return at most `n` available bytes as soon as at least 1 byte is available in the internal buffer. If EOF is received before any byte is read, return an empty bytes object. Returned value is not limited with limit, configured at stream creation. If stream was paused, this function will automatically resume it if needed. NrTread) rrrrOrrrrrr)r=nblocksblockrzrrrrss(     zStreamReader.readcs|dkr td|jdur|j|dkrdSt|j|kr@|jr1t|j}|jt||| dIdHt|j|kst|j|krRt|j}|jnt|jd|}|jd|=| |S)aRead exactly `n` bytes. Raise an IncompleteReadError if EOF is reached before `n` bytes can be read. The IncompleteReadError.partial attribute of the exception will contain the partial read bytes. if n is zero, return empty bytes object. Returned value is not limited with limit, configured at stream creation. If stream was paused, this function will automatically resume it if needed. rz*readexactly size can not be less than zeroNr readexactly) rrrrrrrr rrr)r=r incompleterzrrrrs*       zStreamReader.readexactlycCs|SrrrArrr __aiter__rVzStreamReader.__aiter__cs |IdH}|dkrt|S)Nr)rStopAsyncIteration)r=valrrr __anext__s zStreamReader.__anext__)r)r)rWrXrYr_rr>rrrIrrqrrxrryrrrrrrrrrrrrvs&   [3) rrr)__all__r9socketrwarningsr\hasattrr r r rrlogrtasksrrrrrr Protocolr3rrrrrrrsB          "   @qP