o ]Lb@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z m Z mZm Z mZddlmZmZd Zd ZdZd Zd Zeeed ZdZd ZdZdZdZdZd ZdZeeeeeeeedZ dZ!d Z"d Z#d Z$e!e"e#e$dZ%dZ&d Z'e&e'dZ(dZ)d Z*e)e*dZ+dZ,d Z-e,e-dZ.dZ/d Z0e/e0dZ1ee%ee(ee+eieieiee.ee1iZ2e3dZ4ddZ5e j6ddGddde7Z8e j6dddGdd d e7Z9d!d"Z:d#d$Z;d%d&Zd+d,Z?efd-d.Z@d/d0ZAd[d1d2ZBd3d4ZCefd5d6ZDGd7d8d8e7ZEGd9d:d:e7ZFGd;d<dd>e7ZHGd?d@d@e7ZIGdAdBdBe7ZJGdCdDdDeJZKGdEdFdFe7ZLGdGdHdHeLZMiZNgZOdIdJZPGdKdLdLe7ZQGdMdNdNeQZRGdOdPdPeQZSdQdRZTdSdTgiZUGdUdVdVe7ZVGdWdXdXe7ZWGdYdZdZe7ZXdS)\)absolute_importN)_)getattr)attr)encodingerrorpycompatutilwireprototypes)cborutil stringutili)s stream-begins stream-endsencoded )scommand-requests command-datascommand-responseserror-responses text-outputsprogressssender-protocol-settingssstream-settings)snew continuationsmores have-data)reosz~szhumanflags..r|)r iteritemsappendgetjoin)mappingvaluenamemapflagsvalrrr humanflags|s r)T)slotsc@s@eZdZdZeZeZeZeZ eZ eZ dS) frameheaderz&Represents the data in a frame header.N) __name__ __module__ __qualname____doc__riblength requestidstreamid streamflagstypeidr'rrrrr+s r+F)r*reprc@sNeZdZdZeZeZeZeZ eZ eZ e j ddZdS)framezRepresents a parsed frame.c Cshd|j}ttD] \}}||jkr|}nq dt|j|j|jtt |j |tt |ji|j fS)NrsHframe(size=%d; request=%d; stream=%d; streamflags=%s; type=%s; flags=%s))r5r r FRAME_TYPESlenpayloadr2r3r) STREAM_FLAGSr4FRAME_TYPE_FLAGSr"r')selftypenamenamer%rrr__repr__s   zframe.__repr__N)r,r-r.r/rr0r2r3r4r5r'r:r strmethodr@rrrrr7sr7cCshttt|}tdt|}|dd|dd<td|d||||d>|B|d<||dd<|S) z#Assemble a frame into a byte array.z This can be used by user-facing applications and tests for creating frames easily without having to type out a bunch of constants. Request ID and stream IDs are integers. Stream flags, frame type, and flags can be specified by integer or named constant. Flags can be delimited by `|` to bitwise OR them together. If the payload begins with ``cbor:``, the following string will be evaluated as Python literal and the resulting object will be fed into a CBOR encoder. Otherwise, the payload is interpreted as a Python byte string literal.  rrrscbor:N)r2r3r4r5r'r:) splitintr;r8r< startswithr#r streamencoder evalpythonliteral unescapestrrI) sfieldsr2r3r4 frametype frameflagsr:finalstreamflagsflag finalflags validflagsrrrmakeframefromhumanstrings>    rZcCsb|dd|dd|d}td|d\}}}|d}|d @d ?}|d @}t||||||S) zParse a unified framing protocol frame header from a buffer. The header is expected to be in the buffer at offset 0 and the buffer is expected to be large enough to hold a full header. rri@rrBrrr)rE unpack_fromr+)data framelengthr2r3r4 typeflagsrTrUrrr parseheader s   rbcCstt}||}|dkrdS|tkrttd||ft|}||j}t ||jkr=ttd|jt |ft |j |j |j |j|j|S)zRead a unified framing protocol frame from a file object. Returns a 3-tuple of (type, flags, payload) for the decoded frame or None if no frame is available. May raise if a malformed frame is seen. rNs+received incomplete frame: got %d bytes: %ss'frame length error: expected %d; got %d)rCrDreadintorAbortrrbreadr1r9r7r2r3r4r5r')fhheader readcounthr:rrr readframe&s*   rjc csd|i}|r ||d<|r||d<dt|}d} d} |s%| tO} n| tO} |r/| tO} ||||} |t| 7}t| |krM|t|krM| tO} |j|t | | dV| t@s\nq|r | t }d} t|t krpt } n t } | d dks{Jd} |j|t| |dV| rd Sq`d S) zCreate frames necessary to transmit a request to run a command. This is a generator of bytearrays. Each item represents a frame ready to be sent over the wire to a peer. nameargsredirectrKrTr2r5r'r:FrN)r#r rOFLAG_COMMAND_REQUEST_NEW!FLAG_COMMAND_REQUEST_CONTINUATION FLAG_COMMAND_REQUEST_EXPECT_DATAr9 FLAG_COMMAND_REQUEST_MORE_FRAMESrIFRAME_TYPE_COMMAND_REQUESTreDEFAULT_MAX_FRAME_SIZEFLAG_COMMAND_DATA_CONTINUATIONFLAG_COMMAND_DATA_EOSFRAME_TYPE_COMMAND_DATA) streamr2cmdargsdatafh maxframesizeredirectr_offsetr'r:donerrrcreatecommandframesHs^    rcCsJdtddi}|jr||}d}|sdSnd}|j|tt||dS)NrKstatussokTFr2r5r'r:encoded)r#r rOstreamsettingssentencoderIFRAME_TYPE_COMMAND_RESPONSE"FLAG_COMMAND_RESPONSE_CONTINUATION)rxr2overallrrrrcreatecommandresponseokframes rccsj|}d} ||||}|t|7}|t|k}|r!t}nt}|j|t|||dkdV|r4dSq)zACreate an empty payload frame representing command end-of-stream.rTrKrN)flushr9FLAG_COMMAND_RESPONSE_EOSrrIr)rxr2r|r:r~chunkrr'rrrcreatecommandresponseeosframess(  rcCsd|j|jdd}dD]}t||}|dur ||dt|<q dt|}|jr4| |}d}nd}|j |t t ||d S) Nrm)surls mediatype)rlocation)size fullhashes fullhashseedserverdercertsservercadercertsrrKTFr) url mediatyperr bytestrr#r rOrrrIrr)rxr2locationr_ar%r:rrrr$createalternatelocationresponseframes,  rccsHdd|id}|r||dd<dt|}|j|tt|dVdS)Nerrormessage)rrrlrKrn)r#r rOrIrr)rxr2messagerzmrrrrcreatecommanderrorresponses  rccsFt|tks Jdt|d|igd}|j|td|dVdS)NrKmsg)typerrrn)r9rtr#r rOrIFRAME_TYPE_ERROR_RESPONSE)rxr2msgerrtyper:rrrcreateerrorframes  rc csg}|D]V\}}}t|tstd|D] }t|ts tdq|D] } t| ts.tdq#|ddd}dd|D}dd|D}d |i} |rP|| d <|rV|| d <|| qd t|} t | |krntd |j |t d| dVdS)aCreate a text output frame to render text to people. ``atoms`` is a 3-tuple of (formatting string, args, labels). The formatting string contains ``%s`` tokens to be replaced by the corresponding indexed entry in ``args``. ``labels`` is an iterable of formatters to be applied at rendering time. In terms of the ``ui`` class, each atom corresponds to a ``ui.write()``. s!must use bytes formatting stringssmust use bytes for argumentssmust use bytes for labelsasciireplacecSg|] }|dddqS)zutf-8rdecoder)rrrrr 7z)createtextoutputframe..cSr)rstrictr)rrHrrrr:rrrlslabelsrKs$cannot encode data in a single framerrnN) isinstancebytes ValueErrorrrr!r#r rOr9rIFRAME_TYPE_TEXT_OUTPUT) rxr2atomsr| atomdicts formattingrzlabelsarglabelatomr:rrrcreatetextoutputframes>       rc@s,eZdZdZefddZddZddZdS) bufferingcommandresponseemitteraHelper object to emit command response frames intelligently. Raw command response data is likely emitted in chunks much smaller than what can fit in a single frame. This class exists to buffer chunks until enough data is available to fit in a single frame. TODO we'll need something like this when compression is supported. So it might make sense to implement this functionality at the stream level. cCs"||_||_||_g|_d|_dSNr)_stream _requestid_maxsize_chunks _chunkssize)r=rxr2r|rrr__init__]s  z(bufferingcommandresponseemitter.__init__ccs |dur|D]}|Vq dS|j|}|sdSt||jkrT|D]}|Vq&d} ||||j}|t|7}|jj|jtt|ddV|t|krSdSq/t||j |jkro|j ||j t|7_ dS|D]}|Vqs|j |t||_ dS)zSend new data for emission. Is a generator of new frames that were derived from the new input. If the special input ``None`` is received, flushes all buffered data to frames. NrTr5r'r:r) _flushrrr9rrIrrrrrr!)r=r_r7r~rrrrsenddsB        z$bufferingcommandresponseemitter.sendccsZd|j}t||jksJg|jdd<d|_|sdS|jj|jtt |ddVdS)NrKrTr) r#rr9rrrrIrrr)r=r:rrrrs  z&bufferingcommandresponseemitter._flushN)r,r-r.r/rtrrrrrrrrQs   Drc@s0eZdZdZddZddZddZdd Zd S) identityencoderz3Encoder for the "identity" stream encoding profile.cCsdSNrr=uirrrrzidentityencoder.__init__cC|Srrr=r_rrrrrzidentityencoder.encodecCdSNrKrr=rrrrrzidentityencoder.flushcCrrrrrrrfinishrzidentityencoder.finishN)r,r-r.r/rrrrrrrrrs  rc@s eZdZdZddZddZdS)identitydecoderz3Decoder for the "identity" stream encoding profile.cCs|r ttddS)Ns6identity decoder received unexpected additional values)rrdrr=r extraobjsrrrrs zidentitydecoder.__init__cCrrrrrrrrrzidentitydecoder.decodeN)r,r-r.r/rrrrrrrs rc@,eZdZddZddZddZddZd S) zlibencodercCsddl}||_||_dSr)zlib_zlib compressobj _compressor)r=rrrrrrszzlibencoder.__init__cC |j|Srrcompressrrrrr zzlibencoder.encodecC|j|jjSr)rrr Z_SYNC_FLUSHrrrrrszzlibencoder.flushcC|j|jj}d|_|Sr)rrrZ_FINISHr=resrrrrzzlibencoder.finishNr,r-r.rrrrrrrrrs  rc@eZdZddZddZdS) zlibdecodercCs(ddl}|r ttd||_dS)Nrs2zlib decoder received unexpected additional values)rrrdr decompressobj _decompressor)r=rrrrrrrs zzlibdecoder.__init__cCs$tjs t|tr t|}|j|Sr)r ispy3rrCrr decompressrrrrrs zzlibdecoder.decodeNr,r-r.rrrrrrrs rc@r) zstdbaseencodercCs,ddlm}||_|j|d}||_dS)Nrzstd)level)r_zstdZstdCompressorrr)r=rrcctxrrrrs  zzstdbaseencoder.__init__cCrrrrrrrr rzzstdbaseencoder.encodecCrr)rrrCOMPRESSOBJ_FLUSH_BLOCKrrrrrszzstdbaseencoder.flushcCrr)rrrCOMPRESSOBJ_FLUSH_FINISHrrrrrrzzstdbaseencoder.finishNrrrrrrs  rceZdZfddZZS)zstd8mbencodercstt|ddS)Nr)superrrr __class__rrrszzstd8mbencoder.__init__r,r-r.r __classcell__rrrrrrc@r)zstdbasedecodercCs&ddlm}|j|d}||_dS)Nrr)max_window_size)rrZstdDecompressorrr)r= maxwindowsizerdctxrrrr"s  zzstdbasedecoder.__init__cCrr)rrrrrrr(rzzstdbasedecoder.decodeNrrrrrr!s rcr)zstd8mbdecodercs(|r ttdtt|jdddS)Ns5zstd8mb decoder received unexpected additional valuesi)r)rrdrrrrrrrrr-s zzstd8mbdecoder.__init__rrrrrr,rrcCstrdSz ddlm}|jWn tyd}Ynw|r(ttftd<tdt t ftd<tdt t ftd<tddS)Nrrszstd-8mbszlibidentity) STREAM_ENCODERSrr __version__ ImportErrorrrSTREAM_ENCODERS_ORDERr!rrrrrrrrpopulatestreamencoders<s        rc@s"eZdZdZdddZddZdS) rxz5Represents a logical unidirectional series of frames.FcCs||_||_dSr)r3_activer=r3activerrrrVs zstream.__init__cCs,d}|js |tO}d|_t||j||||S)}Create a frame to be sent out over this stream. Only returns the frame instance. Does not actually send it. rT)r STREAM_FLAG_BEGIN_STREAMrIr3)r=r2r5r'r:r4rrrrIZszstream.makeframeNF)r,r-r.r/rrIrrrrrxSs  rxcs:eZdZdZd fdd ZddZddZd d ZZS) inputstreamz,Represents a stream used for receiving data.Fcstt|j||dd|_dS)Nr )rrr_decoderr rrrrls zinputstream.__init__cCs2|tvr ttd|t|d|||_dS)zSet the decoder for this stream. Receives the stream profile name and any additional CBOR objects decoded from the stream encoding settings frame payloads. sunknown stream decoder: %srN)rrrdrr)r=rr?rrrr setdecoderpszinputstream.setdecodercC|js|S|j|Sr)rrrrrrr{s zinputstream.decodecC|jsdS|jSr)rrrrrrr zinputstream.flushr) r,r-r.r/rrrrrrrrrris  rcsTeZdZdZdfdd ZddZddZd d Zd d Zdd dZ ddZ Z S) outputstreamz*Represents a stream used for sending data.Fcs*tt|j||dd|_d|_d|_dS)NrF)rrrr_encoder _encodernamer rrrrs zoutputstream.__init__cCs6|tvr ttd|t|d||_||_dS)zTSet the encoder for this stream. Receives the stream profile name. sunknown stream encoder: %srN)rrrdrrr)r=rr?rrr setencoders zoutputstream.setencodercCrr)rrrrrrrs zoutputstream.encodecCrr)rrrrrrrrzoutputstream.flushcCs|jsdS|jdSr)rrrrrrrszoutputstream.finishcCs^d}|js |tO}d|_|r|jstd|tO}|tkr%|t@r%d|_t||j ||||S)r rTs@attempting to send encoded frame without sending stream settings) r r rrProgrammingErrorSTREAM_FLAG_ENCODING_APPLIEDFRAME_TYPE_STREAM_SETTINGS!FLAG_STREAM_ENCODING_SETTINGS_EOSrIr3)r=r2r5r'r:rr4rrrrIs"zoutputstream.makeframecCs2|jr|jrdSdt|j}||tt|S)zCreate a stream settings frame for this stream. Returns frame data or None if no stream settings frame is needed or has already been sent. NrK) rrr#r rOrrIrr)r=r2r:rrrmakestreamsettingsframes z$outputstream.makestreamsettingsframer) r,r-r.r/rrrrrrIrrrrrrrs  rcCs|jdr td|jdS)NrsAserver should only write to even numbered streams; %d is not even)r3rr)rxrrrensureserverstreams rcontentencodingsrc@seZdZdZd(ddZddZddZd d Zd d Zd dZ d)ddZ ddZ ddZ ddZ ddZddZddZddZd d!Zd"d#Zd$d%Zd&d'ZdS)* serverreactora> Holds state of a server handling frame-based protocol requests. This class is the "brain" of the unified frame-based protocol server component. While the protocol is stateless from the perspective of requests/commands, something needs to track which frames have been received, what frames to expect, etc. This class is that thing. Instances are modeled as a state machine of sorts. Instances are also reactionary to external events. The point of this class is to encapsulate the state of the connection and the exchange of frames, not to perform work. Instead, callers tell this class when something occurs, like a frame arriving. If that activity is worthy of a follow-up action (say *run a command*), the return value of that handler will say so. I/O and CPU intensive operations are purposefully delegated outside of this class. Consumers are expected to tell instances when events occur. They do so by calling the various ``on*`` methods. These methods return a 2-tuple describing any follow-up action(s) to take. The first element is the name of an action to perform. The second is a data structure (usually a dict) specific to that action that contains more information. e.g. if the server wants to send frames back to the client, the data structure will contain a reference to those frames. Valid actions that consumers can be instructed to take are: sendframes Indicates that frames should be sent to the client. The ``framegen`` key contains a generator of frames that should be sent. The server assumes that all frames are sent to the client. error Indicates that an error occurred. Consumer should probably abort. runcommand Indicates that the consumer should run a wire protocol command. Details of the command to run are given in the data structure. wantframe Indicates that nothing of interest happened and the server is waiting on more frames from the client before anything interesting can be done. noop Indicates no additional action is required. Known Issues ------------ There are no limits to the number of partially received commands or their size. A malicious client could stream command request data and exhaust the server's memory. Partially received commands are not acted upon when end of input is reached. Should the server error if it receives a partial request? Should the client send a message to abort a partially transmitted request to facilitate graceful shutdown? Active requests that haven't been responded to aren't tracked. This means that if we receive a command and instruct its dispatch, another command with its request ID can come in over the wire and there will be a race between who responds to what. FcCsR||_||_d|_d|_g|_i|_i|_i|_t|_ d|_ t t |_ tdS)aConstruct a new server reactor. ``deferoutput`` can be used to indicate that no output frames should be instructed to be sent until input has been exhausted. In this mode, events that would normally generate output frames (such as a command response being ready) will instead defer instructing the consumer to send those frames. This is useful for half-duplex transports where the sender cannot receive until all data has been transmitted. initialrN)_ui _deferoutput_state_nextoutgoingstreamid_bufferedframegens_incomingstreams_outgoingstreams_receivingcommandsset_activecommands_protocolsettingsdecoderdictDEFAULT_PROTOCOL_SETTINGS_sendersettingsr)r=r deferoutputrrrr-s   zserverreactor.__init__cCs|jdsd|_|td|jS|j|jvr0|jt@s'd|_|tdSt|j|j|j<|jt@r=d|_t d|jt @rG|j|j=|j |j |j|j|jd}||j}|sdt d|j||S)zProcess a frame that has been received off the wire. Returns a dict with an ``action`` key that details what action, if any, the consumer should take next. rerroreds/received frame with even numbered stream ID: %dsNreceived frame on unknown inactive stream without beginning of stream flag sets8support for decoding stream payloads not yet implemented)r"protocol-settings-receivingidlecommand-receivingr2sunhandled state: %s)r3r%_makeerrorresultrr(r4r rrrrSTREAM_FLAG_END_STREAM_onframeinitial_onframeprotocolsettings _onframeidle_onframecommandreceiving_onframeerroredr")r=r7handlersmethrrr onframerecvMsB       zserverreactor.onframerecvcs8tttr tfdd}|S)zSignal that objects are ready to be sent to the client. ``objs`` is an iterable of objects (typically a generator) that will be encoded via CBOR and added to frames, which will be sent to the client. c 3sXd}d}t} zt}Wnfty2|dD]}|Vq|r0tD]}|Vq*YntjyS}zt|j|j D]}|VqCWYd}~nd}~wt yw}zt dt |ddD]}|VqgWYd}~nd}~wwzt|tjr|rtd}|r|Vt|Vd}d}Wq |rtd|s}|r|Vt}|r|Vd}t|tjr||jD]}|Vqn.t|tjrt|jD] }||D]}|Vqqnt|D] }||D]}|VqqWn$t y"}zt d|ddD]}|VqWYd}~nd}~wwq jdS)NFTs%sserverrs:alternatelocationresponse seen after initial output objects(object follows alternatelocationresponse)rnext StopIterationrrrWireprotoCommandErrorrr messageargs Exceptionrr forcebytestrrr alternatelocationresponserrrrencodedresponser_indefinitebytestringresponser streamencodebytestringfromiterchunksrOr,remove)emittedalternatelocationsentemitteror7erobjsr2r=rxrr sendframess                 kz?serverreactor.oncommandresponsereadyobjects..sendframes)rrlistiter_handlesendframes)r=rxr2rTrUrrSroncommandresponsereadyobjects~s   qz+serverreactor.oncommandresponsereadyobjectscs.jrjs difSfdd}dd|ifS)zSignals that end of input has been received. No more frames will be received. All pending activity should be completed. noopc3s"jD] }|D]}|VqqdSr)r')genr7rrrmakegens  z)serverreactor.oninputeof..makegen sendframesframegen)r$r')r=r\rrr oninputeof s  zserverreactor.oninputeofcCs&|jr |j|difSdd|ifS)NrZr]r^)r$r'r!)r=framegenrrrrX s  zserverreactor._handlesendframescs&tfdd}|S)Nc3s.tddD]}|Vq jdS)Nr@rA)rr,rMr7rr2r=rxrrrU,s  z/serverreactor.onservererror..sendframesrrX)r=rxr2rrUrrbr onservererror)s zserverreactor.onservererrorNcs(tfdd}|S)zACalled when a command encountered an error before sending output.c3s,tD]}|VqjdSr)rr,rMrarzrr2r=rxrrrU:s z0serverreactor.oncommanderror..sendframesrc)r=rxr2rrzrUrreroncommanderror6s zserverreactor.oncommanderrorcCsV|j}|jd7_t|}||j|<tD]}||jdvr(||j||Sq|S)zCreate a stream to be used for sending data to the client. If this is called before protocol settings frames are received, we don't know what stream encodings are supported by the client and we will default to identity. rr )r&rr)rr0rr#)r=r3rRr?rrrmakeoutputstreamDs zserverreactor.makeoutputstreamcCs dd|ifS)Nrrr)r=rrrrr6Zszserverreactor._makeerrorresultcCs|j|}|dsd|_td|j|=|jrd|_nd|_|ddt|dd}d|vr?d|_|t d Sd |vrGi|d <||j vsNJ|j |d ||d|d | d |d rm|d dfSddfS)N requestdoner2s,should not be called without requestdone setr5r4payloadrrks$command request missing "name" fieldrls runcommandrmdata)s requestidscommandrlrmrj) r*r%rrseekr decodeallgetvaluer6rr,addr")r=r2entryrequestrrr_makeruncommandresult_s@  z#serverreactor._makeruncommandresultcCsdd|jifS)Ns wantframesstate)r%rrrr_makewantframeresultsz"serverreactor._makewantframeresultcCsT|jt@}|jt@}|r|rd|_|tdS|s&|s(d|_|tdSdSdS)Nr2sGreceived command request frame with both new and continuation flags setsJreceived command request frame with neither new nor continuation flags set)r'rorpr%r6r)r=r7new continuationrrr_validatecommandrequestframes"  z*serverreactor._validatecommandrequestframecCsX|jtkrd|_t|_||S|jtkrd|_||Sd|_| t d|jS)Nr3r4r2sBexpected sender protocol settings or command request frame; got %d) r5#FRAME_TYPE_SENDER_PROTOCOL_SETTINGSr%r bufferingdecoderr-r9rsr:r6rr=r7rrrr8s     zserverreactor._onframeinitialc Csj|jdksJ|jdusJ|jtkr d|_|td|jS|jt@}|jt@}|r8|r8d|_|tdS|sF|sFd|_|tdSz |j |j Wn!t yp}zd|_|tdt |WYd}~Sd}~ww|rw|S|s{J|j}d|_|sd|_|tdSt|dkrd|_|td S|d }d |vr|d |jd <d |_|S) Nr3r2s/expected sender protocol settings frame; got %dsXsender protocol settings frame cannot have both continuation and end of stream flags setsOsender protocol settings frame must have continuation or end of stream flag sets;error decoding CBOR from sender protocol settings frame: %ss8sender protocol settings frame did not contain CBOR datars=sender protocol settings frame contained multiple CBOR valuesrr r4)r%r-r5rvr6rr'*FLAG_SENDER_PROTOCOL_SETTINGS_CONTINUATION!FLAG_SENDER_PROTOCOL_SETTINGS_EOSrr:rFr rGrr getavailabler9r0)r=r7moreeosrRdecodeddrrrr9sx       z&serverreactor._onframeprotocolsettingscCs|jtkrd|_|td|jS||}|r|S|j|jvr.d|_|td|jS|j|jvrAd|_|td|jS|j t @}|j t @}|j t @}|s\d|_|tdSt }||j|d| t|d|j|j<|s~|s~||jS|s|sJd|_|S)Nr2s&expected command request frame; got %ds#request with ID %d already receiveds$request with ID %d is already actives3received command request frame without new flag set)rirjrh expectingdatar5)r5rsr%r6rrur2r*r,r'rorrrqr bytesiowriter:boolrqrr)r=r7rrs moreframes expectingdatar:rrrr:sL             zserverreactor._onframeidlecCs|jtkr|jt@r||S||}|r|S|j|jvr+d|_| t d|jS|j|j vr>d|_| t d|jS|j |j}|jtkr|jt @}t |jt@}|drcd|_| t dS||dkrsd|_| t dS|d|j|sd |d<|s|s||jS|S|jtkr|dsd|_| t d |jS|d durt|d <|||Sd|_| t d |jS) Nr2s3received frame for request that is still active: %ds4received frame for request that is not receiving: %drhsGreceived command request frame when request frames were supposedly doners4mismatch between expect data flag and previous frameriTsFreceived command data frame for request that is not expecting data: %drjs"received unexpected frame type: %d)r5rsr'ror:rur2r,r%r6rr*rrrrqrr:rqrrrwr r_handlecommanddataframe)r=r7rrorrrrrr;;sv                z&serverreactor._onframecommandreceivingcCsh|jtksJ|d|j|jt@r|S|jt@r*|dd| |j Sd|_ | t dS)Nrjrr2s command data frame without flags)r5rwrr:r'rurrrvrkrqr2r%r6r)r=r7rorrrrs   z%serverreactor._handlecommanddataframecCs|tdS)Nsserver already errored)r6rrxrrrr<szserverreactor._onframeerroredrr)r,r-r.r/rr?rYr_rXrdrfrgr6rqrrrur8r9r:r;rr<rrrrr!s* @ 1 +L5N r!c@seZdZdZdddZdS)commandrequestz&Represents a request to run a command.NcCs(||_||_||_||_||_d|_dS)Nspending)r2r?rzr{r}state)r=r2r?rzr{r}rrrrs  zcommandrequest.__init__NN)r,r-r.r/rrrrrrsrc@sZeZdZdZ   dddZdddZd d Zd d Zd dZddZ ddZ ddZ dS) clientreactoraHolds state of a client issuing frame-based protocol requests. This is like ``serverreactor`` but for client-side state. Each instance is bound to the lifetime of a connection. For persistent connection transports using e.g. TCP sockets and speaking the raw framing protocol, there will be a single instance for the lifetime of the TCP socket. For transports where there are multiple discrete interactions (say tunneled within in HTTP request), there will be a separate instance for each distinct interaction. Consumers are expected to tell instances when events occur by calling various methods. These methods return a 2-tuple describing any follow-up action(s) to take. The first element is the name of an action to perform. The second is a data structure (usually a dict) specific to that action that contains more information. e.g. if the reactor wants to send frames to the server, the data structure will contain a reference to those frames. Valid actions that consumers can be instructed to take are: noop Indicates no additional action is required. sendframes Indicates that frames should be sent to the server. The ``framegen`` key contains a generator of frames that should be sent. The reactor assumes that all frames in this generator are sent to the server. error Indicates that an error occurred. The ``message`` key contains an error message describing the failure. responsedata Indicates a response to a previously-issued command was received. The ``request`` key contains the ``commandrequest`` instance that represents the request this data is for. The ``data`` key contains the decoded data from the server. ``expectmore`` and ``eos`` evaluate to True when more response data is expected to follow or we're at the end of the response stream, respectively. FTNcCs`||_||_||_||_d|_d|_d|_d|_td|_ t |_ i|_ i|_i|_tdS)aCreate a new instance. ``hasmultiplesend`` indicates whether multiple sends are supported by the transport. When True, it is possible to send commands immediately instead of buffering until the caller signals an intent to finish a send operation. ``buffercommands`` indicates whether sends should be buffered until the last request has been issued. ``clientcontentencoders`` is an iterable of content encoders the client will advertise to the server and that the server can use for encoding data. If not defined, the client will not advertise content encoders to the server. TFrN)r#_hasmultiplesend _buffersends_clientcontentencoders_canissuecommands_cansend_protocolsettingssent_nextrequestidr_outgoingstream collectionsdeque_pendingrequests_activerequestsr(_streamsettingsdecodersr)r=rhasmultiplesend buffersendsclientcontentencodersrrrrs   zclientreactor.__init__cCs|jstd|j}|jd7_t|||||d}|jr)|j||difS|js1td|j s:d|_d|_|dd| |ifS) aRequest that a command be executed. Receives the command name, a dict of arguments to pass to the command, and an optional file object containing the raw data for the command. Returns a 3-tuple of (request, action, action data). scannot issue new commandsrr{r}rZ*sends cannot be performed on this instanceFr]r^) rrrrrrrr!rr_makecommandframes)r=r?rzr{r}r2rprrr callcommands,     zclientreactor.callcommandcsJjsdifSjstdjsd_d_fdd}dd|ifS)a_Request that all queued commands be sent. If any commands are buffered, this will instruct the caller to send them over the wire. If no commands are buffered it instructs the client to no-op. If instances aren't configured for multiple sends, no new command requests are allowed after this is called. rZrFc3s6jrj}|D]}|VqjsdSdSr)rpopleftr)rpr7rrr makeframes?s  z/clientreactor.flushcommands..makeframesr]r^)rrrrrr)r=rrrr flushcommands's  zclientreactor.flushcommandsccs||j|j<d|_|js*|jr*d|_dtd|ji}|jj |jt t |dVt |j|j|j |j|j|jd}|D]}|Vq||j|_|jt @rH|j|j=|j t krR| |S|j |jvrcddtd|j ifS|j|j }d|_t|jt|ji}||j }|std|j |||S) zProcess a frame that has been received off the wire. Returns a 2-tuple of (action, meta) describing further action the caller needs to take as a result of receiving this frame. rrrs.received frame with odd numbered stream ID: %dsEreceived frame on unknown stream without beginning of stream flag sets*received frame for inactive request ID: %ds receivingsunhandled frame type: %d)r3rr(r4r rrrr:r7r5r_onstreamsettingsframer2rrr_oncommandresponseframer_onerrorresponseframer"rr)r=r7rxrpr=r>rrrr?rsV            zclientreactor.onframerecvc Csv|jtksJ|jt@}|jt@}|r|rddtdifS|s)|s)ddtdifS|j|jvr9t }||j|j<|j|j}z| |j Wnt yf}zddtdt |ifWYd}~Sd}~ww|rmdifS|sqJ|}|j|j=|sddtdifSz|j|j|j|d|d dWdifSt y}zddtd t |ifWYd}~Sd}~ww) NrrsXstream encoding settings frame cannot have both continuation and end of stream flags setsOstream encoding settings frame must have continuation or end of stream flag sets;error decoding CBOR from stream encoding settings frame: %srZs8stream encoding settings frame did not contain CBOR datarrs error setting stream decoder: %s)r5rr'*FLAG_STREAM_ENCODING_SETTINGS_CONTINUATIONrrr3rr rwrr:rFr rGr{r(rr#)r=r7r|r}decoderrRr~rrrrs~        z$clientreactor._onstreamsettingsframecCs:|jt@r d|_|j|j=d||jt@|jt@|jdfS)Nsreceiveds responsedata)requests expectmorerrj)r'rrrr2rr:)r=rpr7rrrrs  z%clientreactor._oncommandresponseframecCs8d|_|j|j=t|jd}d||d|ddfS)Nr2rrrr)rrr)rrr2r rlr:)r=rpr7rrrrr!s z#clientreactor._onerrorresponseframe)FTNr) r,r-r.r/rrrrr?rrrrrrrrs1 )'")HX rr)Y __future__rrrEi18nrr r thirdpartyrrrrr r utilsr r rDrtr r7rr;rsrwrrrFRAME_TYPE_PROGRESSrvrr8rorprrrqFLAGS_COMMAND_REQUESTrurvFLAGS_COMMAND_DATArrFLAGS_COMMAND_RESPONSEryrzFLAGS_SENDER_PROTOCOL_SETTINGSrrFLAGS_STREAM_ENCODING_SETTINGSr<StructARGUMENT_RECORD_HEADERr)rRobjectr+r7rIrZrbrjrrrrrrrrrrrrrrrrrrrrxrrrr/r!rrrrrrs         B' M  % 8n   !U 5