13 lines
825 B
PL/PgSQL
13 lines
825 B
PL/PgSQL
CREATE TABLE auth_limits (bucket text NOT NULL, window_id bigint NOT NULL, count integer NOT NULL, PRIMARY KEY(bucket,window_id));
|
|
-- Both counters increment in one transaction, global key locked first.
|
|
CREATE FUNCTION auth_admit(subject text) RETURNS boolean LANGUAGE plpgsql AS $$
|
|
DECLARE win bigint; total integer; per_subject integer;
|
|
BEGIN
|
|
win := floor(extract(epoch from clock_timestamp()) / 60);
|
|
INSERT INTO auth_limits VALUES ('global',win,1) ON CONFLICT(bucket,window_id) DO UPDATE SET count=auth_limits.count+1 RETURNING count INTO total;
|
|
IF total>120 THEN RETURN false; END IF;
|
|
INSERT INTO auth_limits VALUES (subject,win,1) ON CONFLICT(bucket,window_id) DO UPDATE SET count=auth_limits.count+1 RETURNING count INTO per_subject;
|
|
DELETE FROM auth_limits WHERE window_id<win-1;
|
|
RETURN per_subject<=12;
|
|
END $$;
|