Skip to content

Commit

Permalink
Merge pull request #40 from zhu327/bugfix_resource_header
Browse files Browse the repository at this point in the history
bugfix: resource header rewrite use same lrucache with stage header r…
  • Loading branch information
wklken authored Aug 9, 2023
2 parents 5496f0c + 57a6549 commit 853d5b8
Showing 1 changed file with 62 additions and 4 deletions.
66 changes: 62 additions & 4 deletions src/apisix/plugins/bk-resource-header-rewrite.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,80 @@
-- We undertake not to change the open source license (MIT license) applicable
-- to the current version of the project delivered to anyone in the future.
--

-- bk-resource-header-rewrite
--
-- Rewrite the headers of a request using the plugin configuration.
-- Copy the logic from bk-stage-header-rewrite to avoid using the same LRU cache
-- which may result in incorrect configuration data.
-- If modifications are needed, both bk-stage-header-rewrite should be modified simultaneously.
local plugin = require("apisix.plugins.bk-stage-header-rewrite")
local core = require("apisix.core")
local pairs = pairs

local plugin_name = "bk-resource-header-rewrite"

local HEADER_REWRITE_CACHE_COUNT = 1000
local lrucache = core.lrucache.new({
type = "plugin",
count = HEADER_REWRITE_CACHE_COUNT
})

local _M = {
version = 0.1,
priority = 17420,
name = plugin_name,
schema = core.table.deepcopy(plugin.schema),
check_schema = plugin.check_schema,
rewrite = plugin.rewrite,
check_schema = plugin.check_schema
}

return _M
-- cache pairs processed data for subsequent JIT hit in calculations
local function create_header_operation(header_conf)
local set = {}
local add = {}

if header_conf.add then
for field, value in pairs(header_conf.add) do
core.table.insert_tail(add, field, value)
end
end
if header_conf.set then
for field, value in pairs(header_conf.set) do
core.table.insert_tail(set, field, value)
end
end

return {
add = add,
set = set,
remove = header_conf.remove or {}
}
end

function _M.rewrite(conf, ctx)
local header_op, err = core.lrucache.plugin_ctx(lrucache, ctx, nil, create_header_operation, conf)
if not header_op then
core.log.error("failed to create header operation: ", err)
return
end

local add_cnt = #header_op.add
for i = 1, add_cnt, 2 do
local val = core.utils.resolve_var(header_op.add[i + 1], ctx.var)
local header = header_op.add[i]
core.request.add_header(ctx, header, val)
end

local set_cnt = #header_op.set
for i = 1, set_cnt, 2 do
local val = core.utils.resolve_var(header_op.set[i + 1], ctx.var)
core.request.set_header(ctx, header_op.set[i], val)
end

local remove_cnt = #header_op.remove
for i = 1, remove_cnt do
core.request.set_header(ctx, header_op.remove[i], nil)
end

end

return _M

0 comments on commit 853d5b8

Please sign in to comment.