Skip to content

Commit

Permalink
feat(patch): control the proxy_upstream in lua side
Browse files Browse the repository at this point in the history
  • Loading branch information
oowl committed Dec 18, 2024
1 parent 16274aa commit eec9ff1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
14 changes: 8 additions & 6 deletions lualib/resty/kong/upstream.lua
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ local ffi_str = ffi.string

local NGX_OK = ngx.OK


local next_upstream_table = {
error = 0x00000002,
timeout = 0x00000004,
Expand All @@ -45,30 +46,31 @@ local next_upstream_table = {
http_429 = 0x00000400,
updating = 0x00000800,
off = 0x00001000,
non_idempotent = 0x00004000,
}

function _M.set_upstream_next(...)
local nargs = select("#", ...)
if nargs == 0 then
error("no argument")
return "no argument"
end

local r = get_request()
if not r then
error("no request found")
return "no request found"
end

local arg_table = { ... }
local next_upstream = 0
for i = 1, nargs do
local v = arg_table[i]
if type(v) ~= "string" then
error("argument #" .. i .. " is not a valid argument")
return "argument #" .. i .. " is not a string"
end

local next_upstream_value = next_upstream_table[v]
if not next_upstream_value then
error("argument #" .. i .. " is not a valid argument")
return "argument #" .. i .. " is not a valid argument"
end

next_upstream = bit.bor(next_upstream, next_upstream_value)
Expand All @@ -78,10 +80,10 @@ function _M.set_upstream_next(...)
local rc = C.ngx_http_lua_ffi_set_upstream_next(r, next_upstream, err)

if rc ~= NGX_OK then
error("failed to set upstream next: " .. tostring(ffi_str(err[0])))
return "failed to set upstream next: " .. ffi_str(err[0])
end

return true
return nil
end

return _M
11 changes: 7 additions & 4 deletions t/013-upstream.t
Original file line number Diff line number Diff line change
Expand Up @@ -228,13 +228,16 @@ __DATA__
--- config
access_by_lua_block {
local upstream = require "resty.kong.upstream"
upstream.set_upstream_next("error", "timeout", "http_500", "http_502", "http_503", "http_504", "http_404", "http_403", "http_429", "non_idempotent")
local err = upstream.set_upstream_next("error", "timeout", "http_500", "http_502", "http_503", "http_504", "http_404", "http_403", "http_429", "non_idempotent", "bala")
if err then
ngx.log(ngx.ERR, "failed to set upstream next: ", err)
return ngx.exit(503)
end
}
location =/balancer {
proxy_pass http://balancer;
}
--- pipelined_requests eval
["GET /balancer", "GET /balancer"]
--- response_body eval
["this is backend peer \$TEST_NGINX_RAND_PORT_4", "this is backend peer \$TEST_NGINX_RAND_PORT_4"]
--- error_code eval
[503, 503]

0 comments on commit eec9ff1

Please sign in to comment.