import postgres as pg import resilience/rate_limit.{Admitted, Wait} import shared import std/os import std/process.{type proc} import std/random.{type random} import std/result import std/test.{assert, assert_equal} /// Against a real database when `LOUISE_PG_URL` names one; skipped /// otherwise. fn against_postgres :: check: fn(pg.Pool) -> () / -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let config = result.expect (pg.config url) "a database url" let pool = result.expect (pg.start_pool config 2) "a pool" check pool } } } fn reset :: pool: pg.Pool store: shared.Store table: String -> () / { let run = fn text { pg.with_connection pool fn { pg.query_statement (pg.Statement(text, [])) } } let _ = run "drop table if exists {table}" let _ = run (shared.create_table store) () } @test fn a_shared_bucket_admits_its_rate_then_says_how_long_to_wait :: -> () / { against_postgres fn pool { let store = shared.rates () reset pool store "rates" let try = fn key { shared.admission pool store 2 key } assert_equal (try "a") Ok(Admitted) assert_equal (try "a") Ok(Admitted) match try "a" { Ok(Wait(seconds)) -> assert (seconds >= 1 && seconds <= 30) "a wait" , other -> panic "expected a wait, got {other}" } // another key has its own bucket; 0 a minute admits everything assert_equal (try "b") Ok(Admitted) assert_equal (shared.admission pool store 0 "a") Ok(Admitted) } } /// An app's own table and key column (starfleet's `api_rates(agent)`). @test fn a_store_of_its_own_names_its_table_and_column :: -> () / { against_postgres fn pool { let store = result.expect (shared.store "throttle_test_rates" "agent") "a store" reset pool store "throttle_test_rates" assert_equal (shared.admission pool store 1 "x") Ok(Admitted) match shared.admission pool store 1 "x" { Ok(Wait(_)) -> (), other -> panic "expected a wait, got {other}" } } }