Hello,
I am trying to design an server with asynchronous task.
For some endpoints, the server responds with a 202 “accepted” response and I would like to start here a lwt thread to process a computation.
The way you define a handler for an endpoint in opium is to provide a function that generate the response. the type of the handler Request.t -> Response.t Lwt.t.
A example handler is
(fun _ ->
let resp = (Opium.Response.of_json ~status:(`Code 202) (`Assoc [])) in
Lwt.return resp)
But I would like to start a computation there as a Lwt thread
(fun _ ->
let resp = (Opium.Response.of_json ~status:(`Code 200) (`Assoc [])) in
let _ = (** long computation here **) in
Lwt.return resp)
Does the handler return immediatly after building the response (and thus before the end of the computation) ?
How can I assure that the long computation remains even after the return of the handler ?
won’t work if the “long computation here” is a blocking computation which is not based on Lwt promises - you shouldn’t run blocking computations in a Lwt “thread”.
If your long computation executes for its side effects and is non-blocking based on Lwt promises, then have a look at Lwt.async and Lwt.dont_wait
Edit: If your long computation is not based on Lwt promises, take a look also at Lwt_preemptive.detach which will execute the computation in a Thread.t thread. There is also a Lwt_domain.detach function which will execute it in a domain.
Thank you very much.
Indeed my long computation executes for its side effects and is non-blocking, based on Lwt promises. Lwt.async should do the trick.