1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192(* This file is part of Dream, released under the MIT license. See
LICENSE.md for details, or visit https://github.com/aantron/dream.
Copyright 2021 Anton Bachin *)(* TODO The other major built-in middleware, prefix, is actually just going to
be built-in code. So it's probably best to look into building in request_id,
and getting rid of the concept of built-in middleware. *)moduleDream=Dream__pure.Inmostletname="dream.request_id"letlast_id=Dream.new_global(fun()->ref0)~name:"dream.request_id.last_id"~show_value:(funid->string_of_int!id)letid=Dream.new_local()~name~show_value:(funid->id)letlwt_key=Lwt.new_key()(* TODO Restore the prefix, make the id random, or something else. *)(* TODO Now that the request id is built in, there is no good way for the user
to pass in a prefix... except perhaps through the app. However, this is
probably worth it, because adding request_id to every single middleware
stack is extremely annoying, given that you always want it and it's so cheap
that there is no reason not to use it. It's probably very rare that someone
needs a prefix. *)letassign_request_idnext_handlerrequest=(* Get the last id for this request's app. *)letlast_id_ref:intref=Dream.globallast_idrequestinincrlast_id_ref;letnew_id=string_of_int!last_id_refin(* Store the new id in the request and in the Lwt promise values map for
best-effort delivery to all code that might want the id. Continue into the
rest of the app. *)letrequest=Dream.with_localidnew_idrequestinLwt.with_valuelwt_key(Somenew_id)(fun()->next_handlerrequest)letget_option?request()=(* First, try to get the id from the request, if one was provided. *)letrequest_id=matchrequestwith|None->None|Somerequest->Dream.localidrequestin(* If no id was found from the maybe-request, look in the promise-chain-local
storage. *)matchrequest_idwith|Some_->request_id|None->Lwt.getlwt_key(* TODO LATER Maybe it's better to build the request id straight into the
runtime? There's no real cost to it... is there? And when wouldn't the user
want a request id? *)(* TODO LATER List arguments for built-in middlewares: 0 or so cost, highly
beneficial, in some cases (prefix) actually necessary for correct operation
of a website. *)