Skip to content

Commit

Permalink
refactor(plugin/response-ratelimiting): unify the response header pro…
Browse files Browse the repository at this point in the history
…cessing using private PDK functions
  • Loading branch information
ADD-SP committed Jun 11, 2024
1 parent c4b8afc commit 37ae038
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions kong/plugins/response-ratelimiting/header_filter.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
local kong_string = require "kong.tools.string"
local pdk_private_rl = require "kong.pdk.private.rate_limiting"


local kong = kong
Expand All @@ -10,10 +11,8 @@ local tonumber = tonumber
local math_max = math.max
local strip = kong_string.strip
local split = kong_string.split


local RATELIMIT_LIMIT = "X-RateLimit-Limit"
local RATELIMIT_REMAINING = "X-RateLimit-Remaining"
local pdk_rl_set_response_headers = pdk_private_rl.set_response_headers
local pdk_rl_set_limit_by_with_identifier = pdk_private_rl.set_limit_by_with_identifier


local function parse_header(header_value, limits)
Expand Down Expand Up @@ -63,16 +62,12 @@ function _M.execute(conf)
end

local stop
local ngx_ctx = ngx.ctx
for limit_name in pairs(usage) do
for period_name, lv in pairs(usage[limit_name]) do
if not conf.hide_client_headers then
-- increment_value for this current request
local limit_hdr = RATELIMIT_LIMIT .. "-" .. limit_name .. "-" .. period_name
local remain_hdr = RATELIMIT_REMAINING .. "-" .. limit_name .. "-" .. period_name
kong.response.set_header(limit_hdr, lv.limit)

local remain = math_max(0, lv.remaining - (increments[limit_name] and increments[limit_name] or 0))
kong.response.set_header(remain_hdr, remain)
pdk_rl_set_limit_by_with_identifier(ngx_ctx, period_name, lv.limit, remain, nil, limit_name)
end

if increments[limit_name] and increments[limit_name] > 0 and lv.remaining <= 0 then
Expand All @@ -81,6 +76,9 @@ function _M.execute(conf)
end
end

-- Set rate-limiting response headers
pdk_rl_set_response_headers(ngx_ctx)

kong.response.clear_header(conf.header_name)

-- If limit is exceeded, terminate the request
Expand Down

0 comments on commit 37ae038

Please sign in to comment.