Skip to content

Commit

Permalink
refactor rate limits
Browse files Browse the repository at this point in the history
  • Loading branch information
abelanger5 committed Aug 8, 2024
1 parent f474d57 commit c165fb1
Show file tree
Hide file tree
Showing 8 changed files with 609 additions and 44 deletions.
59 changes: 59 additions & 0 deletions pkg/repository/prisma/dbsqlc/rate_limits.sql
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,62 @@ INSERT INTO "RateLimit" (
"limitValue" = sqlc.arg('limit')::int,
"window" = COALESCE(sqlc.narg('window')::text, '1 minute')
RETURNING *;

-- name: ListRateLimitsForTenant :many
WITH refill AS (
UPDATE
"RateLimit" rl
SET
"value" = CASE
WHEN NOW() - rl."lastRefill" >= rl."window"::INTERVAL THEN
get_refill_value(rl)
ELSE
rl."value"
END,
"lastRefill" = CASE
WHEN NOW() - rl."lastRefill" >= rl."window"::INTERVAL THEN
CURRENT_TIMESTAMP
ELSE
rl."lastRefill"
END
WHERE
rl."tenantId" = @tenantId::uuid
RETURNING *
)
SELECT
refill.*,
-- return the next refill time
(refill."lastRefill" + refill."window"::INTERVAL)::timestamp AS "nextRefillAt"
FROM
refill;

-- name: ListRateLimitsForSteps :many
SELECT
*
FROM
"StepRateLimit" srl
WHERE
srl."stepId" = ANY(@stepIds::uuid[])
AND srl."tenantId" = @tenantId::uuid;

-- name: BulkUpdateRateLimits :many
UPDATE
"RateLimit" rl
SET
"value" = get_refill_value(rl) - input."units",
"lastRefill" = CASE
WHEN NOW() - rl."lastRefill" >= rl."window"::INTERVAL THEN
CURRENT_TIMESTAMP
ELSE
rl."lastRefill"
END
FROM
(
SELECT
unnest(@keys::text[]) AS "key",
unnest(@units::int[]) AS "units"
) AS input
WHERE
rl."key" = input."key"
AND rl."tenantId" = @tenantId::uuid
RETURNING rl.*;
163 changes: 163 additions & 0 deletions pkg/repository/prisma/dbsqlc/rate_limits.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit c165fb1

Please sign in to comment.