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 17, 2024
1 parent f0fc178 commit 9c0aad4
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions kong/plugins/response-ratelimiting/header_filter.lua
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
local kong_string = require "kong.tools.string"
local pdk_private_rl = require "kong.pdk.private.rate_limiting"


local kong = kong
local next = next
local type = type
local pairs = pairs
local ipairs = ipairs
local tonumber = tonumber
local math_max = math.max
local strip = require("kong.tools.string").strip
local split = require("kong.tools.string").split


local RATELIMIT_LIMIT = "X-RateLimit-Limit"
local RATELIMIT_REMAINING = "X-RateLimit-Remaining"
local strip = kong_string.strip
local split = kong_string.split
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 @@ -60,16 +64,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 @@ -78,6 +78,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

1 comment on commit 9c0aad4

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bazel Build

Docker image available kong/kong:9c0aad44f3109a457e23883b7e9121be37c218fb
Artifacts available https://github.com/Kong/kong/actions/runs/9541516480

Please sign in to comment.