Files
mtusi2026lab7/migrations/007_login_cpu_budget.sql
T

28 lines
1.7 KiB
PL/PgSQL

-- 2 API replicas x 2 CPU: reserve headroom below the measured KDF throughput.
CREATE OR REPLACE FUNCTION login_wait(account text) RETURNS integer
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp AS $$
DECLARE
moment timestamptz := clock_timestamp();
global_tokens double precision; account_tokens double precision;
BEGIN
IF account !~ '^[a-f0-9]{64}$' THEN RAISE EXCEPTION 'Invalid limiter key'; END IF;
INSERT INTO login_buckets VALUES ('global',16,moment) ON CONFLICT DO NOTHING;
SELECT least(16.0,tokens+extract(epoch FROM moment-updated_at)*8.0)
INTO global_tokens FROM login_buckets WHERE bucket='global' FOR UPDATE;
-- Reject before creating arbitrary account buckets: a name flood cannot
-- grow state faster than the eight admitted attempts per second.
IF global_tokens<1 THEN RETURN ceil((1-global_tokens)/8.0)::integer; END IF;
INSERT INTO login_buckets VALUES ('account:'||account,8,moment) ON CONFLICT DO NOTHING;
SELECT least(8.0,tokens+extract(epoch FROM moment-updated_at)*(8.0/60.0))
INTO account_tokens FROM login_buckets WHERE bucket='account:'||account FOR UPDATE;
IF account_tokens<1 THEN RETURN ceil((1-account_tokens)/(8.0/60.0))::integer; END IF;
UPDATE login_buckets SET tokens=global_tokens-1,updated_at=moment WHERE bucket='global';
UPDATE login_buckets SET tokens=account_tokens-1,updated_at=moment WHERE bucket='account:'||account;
DELETE FROM login_buckets WHERE bucket IN (
SELECT bucket FROM login_buckets WHERE updated_at<moment-interval '10 minutes'
AND bucket<>'global' ORDER BY updated_at LIMIT 128
);
RETURN 0;
END $$;
REVOKE ALL ON FUNCTION login_wait(text) FROM PUBLIC;