Skip to content

Commit

Permalink
fix(plugins/bk-traffic-label.lua): remove weight normalized, use raw …
Browse files Browse the repository at this point in the history
…weight
  • Loading branch information
wklken committed Nov 22, 2024
1 parent f81fe7e commit 3aad0e8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 20 deletions.
23 changes: 6 additions & 17 deletions src/apisix/plugins/bk-traffic-label.lua
Original file line number Diff line number Diff line change
Expand Up @@ -103,30 +103,19 @@ function _M.check_schema(conf)
end
total_weight = total_weight + action.weight
end

-- Normalize the weight of each action
local accumulated_weight = 0
for i, action in ipairs(rule.actions) do
if i == #rule.actions then
-- Assign the remaining weight to the last action to ensure the total is 100
action.weight = 100 - accumulated_weight
else
action.weight = math.floor(action.weight / total_weight * 100)
accumulated_weight = accumulated_weight + action.weight
end
end
rule.total_weight = total_weight
end
end

return true
end

local function apply_actions(actions, ctx)
-- Generate a random number between 0 and 100
local random_weight = math.random(0, 100)
local function apply_actions(rule, ctx)
-- Generate a random number between 1 and total_weight, [1, total_weight]
local random_weight = math.random(1, rule.total_weight)
local current_weight = 0

for _, action in ipairs(actions) do
for _, action in ipairs(rule.actions) do
current_weight = current_weight + action.weight
-- Apply the action if the random number falls within the current weight range
if random_weight <= current_weight then
Expand All @@ -153,7 +142,7 @@ function _M.access(conf, ctx)
local match_passed = ex:eval(ctx.var)
if match_passed then
-- Apply the actions if the match condition is met
apply_actions(rule.actions, ctx)
apply_actions(rule, ctx)
end
end
end
Expand Down
7 changes: 4 additions & 3 deletions src/apisix/tests/test-bk-traffic-label.lua
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ describe(
local ok, err = plugin.check_schema(conf)
assert.is_true(ok)
assert.is_nil(err)
assert.is_equal(conf.rules[1].actions[1].weight, 33)
assert.is_equal(conf.rules[1].actions[2].weight, 33)
assert.is_equal(conf.rules[1].actions[3].weight, 34)
assert.is_equal(conf.rules[1].actions[1].weight, 1)
assert.is_equal(conf.rules[1].actions[2].weight, 1)
assert.is_equal(conf.rules[1].actions[3].weight, 1)
assert.is_equal(conf.rules[1].total_weight, 3)
end
)
end
Expand Down

0 comments on commit 3aad0e8

Please sign in to comment.