123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276(*----------------------------------------------------------------------------
Copyright (c) 2017 Inhabited Type LLC.
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.
----------------------------------------------------------------------------*)typeerror=[`Bad_request|`Bad_gateway|`Internal_server_error|`Exnofexn]typeerror_handler=?request:Request.t->error->(Headers.t->Body.Writer.t)->unitmoduleReader=Parse.ReadermoduleWriter=Serialize.Writer(* XXX(seliopou): The current design assumes that a new [Reqd.t] will be
* allocated for each new request/response on a connection. This is wasteful,
* as it creates garbage on persistent connections. A better approach would be
* to allocate a single [Reqd.t] per connection and reuse it across
* request/responses. This would allow a single [Faraday.t] to be allocated for
* the body and reused. The [response_state] type could then be inlined into
* the [Reqd.t] record, with dummy values occuping the fields for [response].
* Something like this:
*
* {[
* type 'handle t =
* { mutable request : Request.t
* ; mutable request_body : Response.Body.Reader.t
* ; mutable response : Response.t (* Starts off as a dummy value,
* * using [(==)] to identify it when
* * necessary *)
* ; mutable response_body : Response.Body.Writer.t
* ; mutable persistent : bool
* ; mutable response_state : [ `Waiting | `Started | `Streaming ]
* }
* ]}
*
* *)typet={request:Request.t;request_body:Body.Reader.t;reader:Reader.request;writer:Writer.t;response_body_buffer:Bigstringaf.t;error_handler:error_handler;mutablepersistent:bool;mutableresponse_state:Response_state.t;mutableerror_code:[`Ok|error]}letcreateerror_handlerrequestrequest_bodyreaderwriterresponse_body_buffer={request;request_body;reader;writer;response_body_buffer;error_handler;persistent=Request.persistent_connectionrequest;response_state=Waiting;error_code=`Ok}letrequest{request;_}=requestletrequest_body{request_body;_}=request_bodyletresponse{response_state;_}=matchresponse_statewith|Waiting->None|Streaming(response,_)|Fixedresponse|Upgrade(response,_)->Someresponseletresponse_exn{response_state;_}=matchresponse_statewith|Waiting->failwith"httpaf.Reqd.response_exn: response has not started"|Streaming(response,_)|Fixedresponse|Upgrade(response,_)->responseletrespond_with_stringtresponsestr=ift.error_code<>`Okthenfailwith"httpaf.Reqd.respond_with_string: invalid state, currently handling error";matcht.response_statewith|Waiting->(* XXX(seliopou): check response body length *)Writer.write_responset.writerresponse;Writer.write_stringt.writerstr;ift.persistentthent.persistent<-Response.persistent_connectionresponse;t.response_state<-Fixedresponse;Writer.wakeupt.writer;|Streaming_|Upgrade_->failwith"httpaf.Reqd.respond_with_string: response already started"|Fixed_->failwith"httpaf.Reqd.respond_with_string: response already complete"letrespond_with_bigstringtresponse(bstr:Bigstringaf.t)=ift.error_code<>`Okthenfailwith"httpaf.Reqd.respond_with_bigstring: invalid state, currently handling error";matcht.response_statewith|Waiting->(* XXX(seliopou): check response body length *)Writer.write_responset.writerresponse;Writer.schedule_bigstringt.writerbstr;ift.persistentthent.persistent<-Response.persistent_connectionresponse;t.response_state<-Fixedresponse;Writer.wakeupt.writer;|Streaming_|Upgrade_->failwith"httpaf.Reqd.respond_with_bigstring: response already started"|Fixed_->failwith"httpaf.Reqd.respond_with_bigstring: response already complete"letunsafe_respond_with_streaming~flush_headers_immediatelytresponse=matcht.response_statewith|Waiting->letencoding=matchResponse.body_length~request_method:t.request.methresponsewith|`Fixed_|`Close_delimited|`Chunkedasencoding->encoding|`Error(`Bad_gateway|`Internal_server_error)->failwith"httpaf.Reqd.respond_with_streaming: invalid response body length"inletresponse_body=Body.Writer.createt.response_body_buffer~encoding~when_ready_to_write:(Optional_thunk.some(fun()->Writer.wakeupt.writer))inWriter.write_responset.writerresponse;ift.persistentthent.persistent<-Response.persistent_connectionresponse;t.response_state<-Streaming(response,response_body);ifflush_headers_immediatelythenWriter.wakeupt.writer;response_body|Streaming_|Upgrade_->failwith"httpaf.Reqd.respond_with_streaming: response already started"|Fixed_->failwith"httpaf.Reqd.respond_with_streaming: response already complete"letrespond_with_streaming?(flush_headers_immediately=false)tresponse=ift.error_code<>`Okthenfailwith"httpaf.Reqd.respond_with_streaming: invalid state, currently handling error";unsafe_respond_with_streaming~flush_headers_immediatelytresponseletunsafe_respond_with_upgradetheadersupgrade_handler=matcht.response_statewith|Waiting->letresponse=Response.create~headers`Switching_protocolsinWriter.write_responset.writerresponse;ift.persistentthent.persistent<-Response.persistent_connectionresponse;t.response_state<-Upgrade(response,upgrade_handler);Writer.flusht.writerupgrade_handler;Body.Reader.closet.request_body;Writer.wakeupt.writer|Streaming_|Upgrade_->failwith"httpaf.Reqd.unsafe_respond_with_upgrade: response already started"|Fixed_->failwith"httpaf.Reqd.unsafe_respond_with_upgrade: response already complete"letrespond_with_upgradetresponseupgrade_handler=ift.error_code<>`Okthenfailwith"httpaf.Reqd.respond_with_streaming: invalid state, currently handling error";unsafe_respond_with_upgradetresponseupgrade_handlerletreport_errorterror=t.persistent<-false;matcht.response_state,t.error_codewith|Waiting,`Ok->t.error_code<-(error:>[`Ok|error]);letstatus=match(error:>[error|Status.standard])with|`Exn_->`Internal_server_error|#Status.standardasstatus->statusint.error_handler~request:t.requesterror(funheaders->letresponse_body=unsafe_respond_with_streamingt~flush_headers_immediately:true(Response.create~headersstatus)in(* NOTE(anmonteiro): When reporting an error that calls the error
handler, we can only deliver an EOF to the request body once the error
response has started. Otherwise, the request body `on_eof` handler
could erroneously send a successful response instead of letting us
handle the error. *)Body.Reader.closet.request_body;response_body)|other->Body.Reader.closet.request_body;matchotherwith|Waiting,`Exn_->(* XXX(seliopou): Decide what to do in this unlikely case. There is an
* outstanding call to the [error_handler], but an intervening exception
* has been reported as well. *)failwith"httpaf.Reqd.report_exn: NYI"|Streaming(_response,response_body),`Ok->Body.Writer.force_closeresponse_body;Reader.wakeupt.reader;|Streaming(_response,response_body),`Exn_->Body.Writer.closeresponse_body;Writer.close_and_draint.writer;Reader.wakeupt.reader;|(Fixed_|Streaming_|Upgrade_|Waiting),_->(* XXX(seliopou): Once additional logging support is added, log the error
* in case it is not spurious. *)()letreport_exntexn=report_errort(`Exnexn)lettry_withtf:(unit,exn)Result.result=tryf();Ok()withexn->report_exntexn;Errorexn(* Private API, not exposed to the user through httpaf.mli *)letclose_request_body{request_body;_}=Body.Reader.closerequest_bodyleterror_codet=matcht.error_codewith|#erroraserror->Someerror|`Ok->Noneletpersistent_connectiont=t.persistentletinput_statet:Input_state.t=matcht.response_statewith|Upgrade_->Ready|_->ifBody.Reader.is_closedt.request_bodythenCompleteelseifBody.Reader.is_read_scheduledt.request_bodythenReadyelseWaitletoutput_statet=Response_state.output_statet.response_stateletflush_request_bodyt=ifBody.Reader.has_pending_outputt.request_bodythentryBody.Reader.execute_readt.request_bodywithexn->report_exntexnletflush_response_bodyt=Response_state.flush_response_bodyt.response_statet.writer