123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112(* Copyright (C) 2014--2018 Petter A. Urkedal <paurkedal@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*)letdefault_max_size=tryint_of_string(Sys.getenv"CAQTI_POOL_MAX_SIZE")withNot_found->8moduleMake(System:Caqti_driver_sig.System_common)=structopenSystemlet(>>=?)mmf=m>>=(functionOkx->mfx|Errore->return(Errore))moduleTask=structtypet={priority:float;mvar:unitMvar.t}letwake{mvar;_}=Mvar.store()mvarletcompare{priority=pA;_}{priority=pB;_}=Pervasives.comparepBpAendmoduleTaskq=Caqti_heap.Make(Task)type('a,+'e)t={p_create:unit->('a,'e)resultfuture;p_free:'a->unitfuture;p_check:'a->(bool->unit)->unit;p_validate:'a->boolfuture;p_max_size:int;mutablep_cur_size:int;p_pool:'aQueue.t;mutablep_waiting:Taskq.t;}letcreate?(max_size=default_max_size)?(check=fun_f->ftrue)?(validate=fun_->returntrue)createfree={p_create=create;p_free=free;p_check=check;p_validate=validate;p_max_size=max_size;p_cur_size=0;p_pool=Queue.create();p_waiting=Taskq.empty}letsize{p_cur_size;_}=p_cur_sizeletwait~priorityp=letmvar=Mvar.create()inp.p_waiting<-Taskq.pushTask.({priority;mvar})p.p_waiting;Mvar.fetchmvarletrecacquire~priorityp=ifQueue.is_emptyp.p_poolthenbeginifp.p_cur_size<p.p_max_sizethenbeginp.p_cur_size<-p.p_cur_size+1;p.p_create()>|=(function|Oke->Oke|Errorerr->p.p_cur_size<-p.p_cur_size-1;Errorerr)endelse(wait~priorityp>>=fun()->acquire~priorityp)endelsebeginlete=Queue.takep.p_poolinp.p_validatee>>=funok->ifokthenreturn(Oke)elsep.p_create()>|=(function|Oke->Oke|Errorerr->p.p_cur_size<-p.p_cur_size-1;Errorerr)endletreleasepe=p.p_checke@@funok->ifokthenQueue.addep.p_poolelsep.p_cur_size<-p.p_cur_size-1;ifnot(Taskq.is_emptyp.p_waiting)thenlettask,taskq=Taskq.pop_ep.p_waitinginp.p_waiting<-taskq;Task.waketaskletuse?(priority=0.0)fp=acquire~priorityp>>=?fune->tryfe>>=(function|Oky->releasepe;return(Oky)|Errorerr->releasepe;return(Errorerr))withexn->releasepe;raiseexnletdisposepe=p.p_freee>|=fun()->p.p_cur_size<-p.p_cur_size-1letrecdrainp=ifp.p_cur_size=0thenreturn()else(ifQueue.is_emptyp.p_poolthenwait~priority:0.0pelsedisposep(Queue.takep.p_pool))>>=fun()->drainpend