123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308(*----------------------------------------------------------------------------
Copyright (c) 2017-2019 Inhabited Type LLC.
Copyright (c) 2019 Antonio Nuno Monteiro.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------*)moduleReader=Parse.ReadermoduleWriter=Serialize.Writertypeerror=[`Malformed_responseofstring|`Invalid_response_body_lengthofResponse.t|`Exnofexn]typeresponse_handler=Response.t->Body.Reader.t->unittypeerror_handler=error->unittypet={config:Config.t;reader:Reader.response;writer:Writer.t;request_queue:Respd.tQueue.t(* invariant: If [request_queue] is not empty, then the head of the queue
has already written the request headers to the wire. *)}letis_closedt=Reader.is_closedt.reader&&Writer.is_closedt.writerletis_waitingt=not(is_closedt)&&Queue.is_emptyt.request_queueletis_activet=not(Queue.is_emptyt.request_queue)letcurrent_respd_exnt=Queue.peekt.request_queueletyield_readertk=Reader.on_wakeupt.readerkletwakeup_readert=Reader.wakeupt.readerletyield_writertk=Writer.on_wakeupt.writerkletwakeup_writert=Writer.wakeupt.writerletcreate?(config=Config.default)()=letrequest_queue=Queue.create()in{config;reader=Reader.responserequest_queue;writer=Writer.create();request_queue}letcreate_request_body~requestt=matchRequest.body_lengthrequestwith|`Fixed0L->Body.Writer.create_empty~writer:t.writer|`Fixed_|`Chunkedasencoding->Body.Writer.create(Bigstringaf.createt.config.request_body_buffer_size)~encoding~writer:t.writer|`Error`Bad_request->failwith"Httpaf.Client_connection.request: invalid body length"letrequestt?(flush_headers_immediately=false)request~error_handler~response_handler=letrequest_body=create_request_body~requesttinletrespd=Respd.createerror_handlerrequestrequest_bodyt.writerresponse_handlerinlethandle_now=Queue.is_emptyt.request_queueinQueue.pushrespdt.request_queue;ifhandle_nowthenRespd.write_requestrespd;ifnotflush_headers_immediatelythenWriter.yieldt.writer;(* Not handling the request now means it may be pipelined.
* `advance_request_queue_if_necessary` will take care of it, but we still
* wanna wake up the writer so that the function gets called. *)wakeup_writert;request_body;;letshutdown_readert=ifis_activetthenRespd.close_response_body(current_respd_exnt);Reader.force_closet.reader;wakeup_readertletshutdown_writert=ifis_activetthenRespd.close_request_body(current_respd_exnt);Writer.closet.writer;wakeup_writertletshutdownt=shutdown_readert;shutdown_writertletset_error_and_handleterror=Queue.iter(funrespd->matchRespd.input_staterespdwith|Wait|Ready->Respd.report_errorrespderror|Complete->matchReader.nextt.readerwith|`Error_|`Read->Respd.report_errorrespderror|_->(* Don't bother reporting errors to responses that have already
* completed. *)())t.request_queue;(* From RFC7230§6.5:
* A client sending a message body SHOULD monitor the network connection
* for an error response while it is transmitting the request. If the
* client sees a response that indicates the server does not wish to
* receive the message body and is closing the connection, the client
* SHOULD immediately cease transmitting the body and close its side of the
* connection. *)shutdownt;;;letunexpected_eoft=set_error_and_handlet(`Malformed_response"unexpected eof");;;letreport_exntexn=set_error_and_handlet(`Exnexn);;exceptionLocalletmaybe_pipeline_queued_requestst=(* Don't bother trying to pipeline if there aren't multiple requests in the
* queue. *)ifQueue.lengtht.request_queue>1thentrylet_=Queue.fold(funprevrespd->beginmatchprevwith|None->()|Someprev->matchrespd.Respd.state,Respd.output_stateprevwith|Uninitialized,Complete->Respd.write_requestrespd;Respd.flush_request_bodyrespd|_->(* bail early. If we can't pipeline this request, we can't write
* next ones either. *)raiseLocalend;Somerespd)Nonet.request_queuein()with|_->()letadvance_request_queuet=ignore(Queue.taket.request_queue);ifnot(Queue.is_emptyt.request_queue)thenbegin(* write request to the wire *)letrespd=current_respd_exntinmatchrespd.statewith|Uninitialized->(* Only write request if it hasn't been written to the wire yet (e.g. via
* pipelining). *)Respd.write_requestrespd;wakeup_writert|_->()endletrec_next_read_operationt=ifnot(is_activet)then(ifReader.is_closedt.readerthenshutdownt;Reader.nextt.reader)else(letrespd=current_respd_exntinmatchRespd.input_staterespdwith|Wait->`Yield|Ready->Reader.nextt.reader|Complete->_final_read_operation_fortrespd)and_final_read_operation_fortrespd=letnext=ifnot(Respd.persistent_connectionrespd)then(shutdown_readert;Reader.nextt.reader;)else(matchRespd.output_staterespdwith|Waiting|Ready->`Yield|Complete->matchReader.nextt.readerwith|`Error_|`Readasoperation->(* Keep reading when in a "partial" state (`Read).
* Don't advance the request queue if in an error state. *)operation|_->advance_request_queuet;_next_read_operationt;)inwakeup_writert;next;;letnext_read_operationt=match_next_read_operationtwith|`Error(`Parse(marks,message))->letmessage=String.concat""[String.concat">"marks;": ";message]inset_error_and_handlet(`Malformed_responsemessage);`Close|`Error(`Invalid_response_body_length_aserror)->set_error_and_handleterror;`Close|`Start->`Read|(`Read|`Yield|`Close)asoperation->operation;;letread_with_moretbs~off~lenmore=letconsumed=Reader.read_with_moret.readerbs~off~lenmoreinifis_activetthenRespd.flush_response_body(current_respd_exnt);consumed;;letreadtbs~off~len=read_with_moretbs~off~lenIncompleteletread_eoftbs~off~len=letbytes_read=read_with_moretbs~off~lenCompleteinifis_activetthenunexpected_eoft;bytes_read;;letrec_next_write_operationt=ifnot(is_activet)then(ifReader.is_closedt.readerthenshutdownt;Writer.nextt.writer)else(letrespd=current_respd_exntinmatchRespd.output_staterespdwith|Waiting->`Yield|Ready->Respd.flush_request_bodyrespd;Writer.nextt.writer|Complete->_final_write_operation_fortrespd)and_final_write_operation_fortrespd=ifnot(Respd.persistent_connectionrespd)then(shutdown_writert;Writer.nextt.writer;)else((* From RFC7230§6.3.2:
* A client that supports persistent connections MAY "pipeline" its
* requests (i.e., send multiple requests without waiting for each
* response). *)maybe_pipeline_queued_requestst;matchRespd.input_staterespdwith|Wait|Ready->wakeup_readert;Writer.nextt.writer;|Complete->matchReader.nextt.readerwith|`Error_->Writer.nextt.writer|_->advance_request_queuet;wakeup_readert;_next_write_operationt);;letnext_write_operationt=_next_write_operationtletreport_write_resulttresult=Writer.report_resultt.writerresult