123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346(* Copyright (C) 2014--2025 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 LGPL-3.0 Linking 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
* and the LGPL-3.0 Linking Exception along with this library. If not, see
* <http://www.gnu.org/licenses/> and <https://spdx.org>, respectively.
*)moduleConfig=Caqti_pool_configletdefault_max_size=tryint_of_string(Sys.getenv"CAQTI_POOL_MAX_SIZE")withNot_found->8letdefault_log_src=Logs.Src.create"Caqti_platform.Pool"moduletypeALARM=sigtypeswitchtypestdenvtypetvalschedule:sw:switch->stdenv:stdenv->Mtime.t->(unit->unit)->tvalunschedule:t->unitendmoduletypeS=sigtypeswitchtypestdenvincludeCaqti_pool_sig.Svalcreate:?config:Caqti_pool_config.t->?check:('a->(bool->unit)->unit)->?validate:('a->boolfiber)->?log_src:Logs.Src.t->sw:switch->stdenv:stdenv->(unit->('a,'e)resultfiber)->('a->unitfiber)->('a,'e)tendmoduleMake(System:System_sig.CORE)(Alarm:ALARMwithtypestdenv:=System.stdenvandtypeswitch:=System.Switch.t)=structopenSystemopenSystem.Fiber.Infixtypereaper_state=|Idle|Working|WaitingofAlarm.tlet(>>=?)mf=m>>=functionOkx->fx|Errore->Fiber.return(Errore)moduleTask=structtypet={priority:float;condition:Condition.t}letwake{condition;_}=Condition.signalconditionletcompare{priority=pA;_}{priority=pB;_}=Float.comparepBpAendmoduleTaskq=Heap.Make(Task)type'aentry={resource:'a;mutableused_count:int;mutableused_latest:Mtime.t;}type('a,+'e)t={stdenv:stdenv;switch:Switch.t;create:unit->('a,'e)resultFiber.t;free:'a->unitFiber.t;check:'a->(bool->unit)->unit;validate:'a->boolFiber.t;log_src:Logs.Src.t;max_idle_size:int;max_idle_age:Mtime.Span.toption;max_size:int;max_use_count:intoption;(* Mutable *)mutex:Mutex.t;mutablecur_size:int;queue:'aentryQueue.t;mutablewaiting:Taskq.t;mutablereaper_state:reaper_state;}(*
let configure c pool =
Option.iter (fun x -> pool.max_size <- x) Config.(get max_size c);
Option.iter (fun x -> pool.max_idle_size <- x) Config.(get max_idle_size c);
Option.iter (fun x -> pool.max_idle_age <- x) Config.(get max_idle_age c);
Option.iter (fun x -> pool.max_use_count <- x) Config.(get max_use_count c)
*)letcreate?(config=Caqti_pool_config.default)?(check=fun_f->ftrue)?(validate=fun_->Fiber.returntrue)?(log_src=default_log_src)~sw~stdenvcreatefree=letmax_size=Config.(getmax_size)config|>Option.value~default:default_max_sizeinletmax_idle_size=Config.(getmax_idle_size)config|>Option.value~default:max_sizeinletmax_idle_age=Config.(getmax_idle_age)config|>Option.value~default:Noneinletmax_use_count=Config.(getmax_use_count)config|>Option.value~default:(Some100)inassert(max_size>0);assert(max_size>=max_idle_size);assert(Option.fold~none:true~some:(funn->n>0)max_use_count);{stdenv;switch=sw;create;free;check;validate;log_src;max_idle_size;max_size;max_use_count;max_idle_age;cur_size=0;queue=Queue.create();waiting=Taskq.empty;reaper_state=Idle;mutex=Mutex.create();}letsizepool=pool.cur_size(* TODO: atomic *)letwait_lck~prioritypool=letcondition=Condition.create()inpool.waiting<-Taskq.pushTask.({priority;condition})pool.waiting;Condition.waitconditionpool.mutexletschedule_lckpool=ifnot(Taskq.is_emptypool.waiting)thenbeginlettask,taskq=Taskq.pop_epool.waitinginpool.waiting<-taskq;Task.waketaskendletreallocpool=leton_error()=Mutex.lockpool.mutex>|=fun()->pool.cur_size<-pool.cur_size-1;schedule_lckpool;Mutex.unlockpool.mutexinFiber.cleanup(fun()->pool.create()>>=(function|Okresource->Fiber.return@@Ok{resource;used_count=0;used_latest=Mtime_clock.now()}|Errorerr->on_error()>|=fun()->Errorerr))on_errorletrecacquire~prioritypool=Mutex.lockpool.mutex>>=fun()->acquire_and_unlock~prioritypoolandacquire_and_unlock~prioritypool=ifQueue.is_emptypool.queuethenbeginifpool.cur_size<pool.max_sizethenbeginpool.cur_size<-pool.cur_size+1;Mutex.unlockpool.mutex;reallocpoolendelsebeginwait_lck~prioritypool>>=fun()->acquire_and_unlock~prioritypoolendendelsebeginletentry=Queue.takepool.queueinMutex.unlockpool.mutex;pool.validateentry.resource>>=funok->ifokthenFiber.return(Okentry)elsebeginLog.warn~src:pool.log_src(funf->f"Dropped pooled connection due to invalidation.")>>=fun()->reallocpoolendendletcan_reuse_lckpoolentry=pool.cur_size<=pool.max_idle_size&&Option.fold~none:true~some:(funn->entry.used_count<n)pool.max_use_countletdispose_expiring_lckpool=letrecprocess_queue_lck()=(* We hold the lock and only release it while freeing resources, which
* means that some other operations may have been processed right before
* each recursive call. *)(matchQueue.peek_optpool.queue,pool.max_idle_agewith|None,_|_,None->Fiber.return()|Someentry,Somemax_idle_age->letnow=Mtime_clock.now()in(matchMtime.add_spanentry.used_latestmax_idle_agewith|None->Logs.warn~src:pool.log_src(funf->f"Cannot schedule pool expiration check due to \
Mtime overflow.");pool.reaper_state<-Idle;Fiber.return()|SomeexpirywhenMtime.comparenowexpiry<0->letalarm=Alarm.schedule~sw:pool.switch~stdenv:pool.stdenvexpiryon_alarminpool.reaper_state<-Waitingalarm;Fiber.return()|Some_->letentry=Queue.takepool.queueinpool.cur_size<-pool.cur_size-1;Mutex.unlockpool.mutex;pool.freeentry.resource>>=fun()->Mutex.lockpool.mutex>>=fun()->assert(pool.reaper_state=Working);process_queue_lck()))andon_alarm()=async~sw:pool.switchbeginfun()->Mutex.lockpool.mutex>>=fun()->pool.reaper_state<-Working;process_queue_lck()>|=fun()->Mutex.unlockpool.mutexendin(matchpool.reaper_state,pool.max_idle_agewith|Idle,None|Working,_|Waiting_,Some_->Fiber.return()|Idle,Some_->pool.reaper_state<-Working;process_queue_lck()|Waitingalarm,None->(* Not reachable unless live reconfiguration is implemented. *)Alarm.unschedulealarm;pool.reaper_state<-Idle;Fiber.return())letreleasepoolentry=Mutex.lockpool.mutex>>=fun()->entry.used_count<-entry.used_count+1;ifnot(can_reuse_lckpoolentry)thenbeginpool.cur_size<-pool.cur_size-1;Mutex.unlockpool.mutex;pool.freeentry.resource>>=fun()->Mutex.lockpool.mutex>|=fun()->schedule_lckpool;Mutex.unlockpool.mutexendelsebeginMutex.unlockpool.mutex;(* TODO: Consider changing the signature of check to return a bool
* Fiber.t to avoid the async call. *)pool.checkentry.resourcebeginfunok->async~sw:pool.switch@@fun()->Mutex.lockpool.mutex>>=fun()->beginifokthenbeginentry.used_latest<-Mtime_clock.now();Queue.addentrypool.queue;dispose_expiring_lckpoolendelsebeginLogs.warn~src:pool.log_src(funf->f"Will not repool connection due to invalidation.");pool.cur_size<-pool.cur_size-1;Fiber.return()endend>|=fun()->schedule_lckpool;Mutex.unlockpool.mutexend;Fiber.return()endletuse?(priority=0.0)fpool=acquire~prioritypool>>=?funentry->Fiber.finally(fun()->fentry.resource)(fun()->releasepoolentry)letrecdrainpool=Mutex.lockpool.mutex>>=fun()->drain_and_unlockpoolanddrain_and_unlockpool=ifpool.cur_size=0thenbegin(matchpool.reaper_statewith|Idle|Working->()|Waitingalarm->Alarm.unschedulealarm;pool.reaper_state<-Idle);Mutex.unlockpool.mutex;Fiber.return()endelse(matchQueue.take_optpool.queuewith|None->wait_lck~priority:0.0pool>>=fun()->drain_and_unlockpool|Someentry->pool.cur_size<-pool.cur_size-1;Mutex.unlockpool.mutex;pool.freeentry.resource>>=fun()->drainpool)endmoduleNo_alarm=structtypet=unitletschedule~sw:_~stdenv:___=()letunschedule_=()endmoduleMake_without_alarm(System:System_sig.CORE)=Make(System)(No_alarm)