ocamlocsigenlwt

How to fully utilise lwt_pool?


I am struggling at the check and validate function for Lwt_pool.create and have some questions here.


val create : 
  int ->

  ?check:('a -> (bool -> unit) -> unit) ->

  ?validate:('a -> bool Lwt.t) -> (unit -> 'a Lwt.t) -> 'a t

First of all, let me describe the background of my usage.

I wish to use Lwt_pool to manage a pool of database connections. The database is MongoDB and the driver was made by myself (Mongo.ml). The driver is actually simple that it is just a TCP (Unix.file_descr) connection to the MongoDB server and send requests / receive responses with the server.


`create n ?check ?validate f` creates a new pool with at most n members. f is the function to use to create a new pool member.

An element of the pool is validated by the optional validate function before its Lwt_pool.use. Invalid elements are re-created.

The optional function check is called after a use of an element failed. It must call its argument excatly one with true if the pool member is still valid and false otherwise.

above is the documentation for create


So here are my questions:

From the doc, I understand validate is to validate the connection before using it.

so my first question is How can I check the availability of a Unix.file_descr? I only know that in order to check it, I have send something through it, right? But if I send something through my connection in order to check, then I guess it would be urgly and I anyway want to send something out via Lwt_pool.use, why bother do similar things before use?


My second question is about check.

So check will be used after use. From the doc, I really can't understand. check is a function which take a my_db_connection (in my case) and a (fun b -> unit) as parameter. Who will provide (fun b -> unit)? Does Lwt_pool itself has such a function? or I should provide it? To do what then?

thanks


Solution

  • I don't know anything about Lwt, but one thing to do is to wait to use a validate function until you see why you would need it. That's why it's an optional parameter (I suspect).

    One thing you can do with a Unix file descriptor is to figure out whether it's attached to a network socket:

    let is_a_socket fd = (Unix.fstat fd).st_kind = S_SOCK
    

    Maybe this will be useful, though someone with Lwt experience can probably give a better answer.