/// At most `limit` jobs at once (ADR 0081): a job that finds every slot /// taken is refused at once (`Full`) instead of waiting, so a burst of /// costly work (password hashing) cannot pile up. A slot is held while /// its job runs, and freed after `lifetime_ms` (30 s with `start`) even /// when its holder died without leaving. /// /// let hashing = gate.start 4 /// match gate.admitted hashing fn { argon2.hash password } /// { Ok(hash) -> ..., Error(gate.Full) -> ... } // 503, try again import std/actor.{Continue} import std/list import std/process.{type Subject, type proc} import std/time @test import std/test.{assert_equal} pub opaque type Gate { Gate(Subject) } @derive Eq Debug Show pub type Full { Full } type Msg { Enter(reply: Subject>), Leave(slot: Int) } type Slots { Slots(held: List<(Int, Int)>, next: Int, limit: Int, lifetime: Int) } pub fn start :: limit: Int -> Gate / { start_with limit 30000 } pub fn start_with :: limit: Int lifetime_ms: Int -> Gate / { Gate( actor.start Slots([], 0, limit, lifetime_ms) fn slots msg { Continue(handled slots msg) } ) } pub fn admitted :: gate: Gate work: fn() -> a / -> Result / { let Gate(subject) = gate match actor.call subject Enter 5000 { Some(slot) -> { let outcome = work () actor.cast subject Leave(slot) Ok(outcome) } , None -> Error(Full) } } fn handled :: slots: Slots msg: Msg -> Slots / { let now = time.in_milliseconds (time.monotonic ()) let live = list.filter slots.held fn held { held.1 > now } match msg { Enter ( reply ) -> if list.length live < slots.limit { process.send reply Some(slots.next) Slots( ..slots , held: [(slots.next, now + slots.lifetime), ..live] , next: slots.next + 1 ) } else { process.send reply None Slots(..slots, held: live) } , Leave(slot) -> Slots(..slots, held: list.filter live fn held { held.0 != slot }) } } @test fn work_is_admitted_while_slots_are_free :: -> () / { let open = start 2 assert_equal (admitted open fn { 1 }) Ok(1) assert_equal (admitted open fn { 2 }) Ok(2) } @test fn work_beyond_the_limit_is_refused_at_once :: -> () / { let narrow = start 1 let _ = process.spawn fn { let _ = admitted narrow fn { process.sleep 1000 } () } process.sleep 10 assert_equal (admitted narrow fn { "late" }) Error(Full) process.sleep 2000 assert_equal (admitted narrow fn { "later" }) Ok("later") } @test fn a_slot_held_past_its_lifetime_is_freed :: -> () / { let narrow = start_with 1 500 let _ = process.spawn fn { let _ = admitted narrow fn { process.sleep 100000 } () } process.sleep 10 assert_equal (admitted narrow fn { "blocked" }) Error(Full) process.sleep 1000 assert_equal (admitted narrow fn { "freed" }) Ok("freed") }