Skip to content

Commit

Permalink
chore: update hold_body_chunk to avoid unexpected behavior (#8045)
Browse files Browse the repository at this point in the history
  • Loading branch information
spacewander authored Oct 10, 2022
1 parent 56d52f0 commit c25e112
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 11 deletions.
22 changes: 11 additions & 11 deletions apisix/core/response.lua
Original file line number Diff line number Diff line change
Expand Up @@ -177,17 +177,6 @@ end
function _M.hold_body_chunk(ctx, hold_the_copy)
local body_buffer
local chunk, eof = arg[1], arg[2]
if eof then
body_buffer = ctx._body_buffer
if not body_buffer then
return chunk
end

body_buffer = concat_tab(body_buffer, "", 1, body_buffer.n)
ctx._body_buffer = nil
return body_buffer
end

if type(chunk) == "string" and chunk ~= "" then
body_buffer = ctx._body_buffer
if not body_buffer then
Expand All @@ -203,6 +192,17 @@ function _M.hold_body_chunk(ctx, hold_the_copy)
end
end

if eof then
body_buffer = ctx._body_buffer
if not body_buffer then
return chunk
end

body_buffer = concat_tab(body_buffer, "", 1, body_buffer.n)
ctx._body_buffer = nil
return body_buffer
end

if not hold_the_copy then
-- flush the origin body chunk
arg[1] = nil
Expand Down
52 changes: 52 additions & 0 deletions t/core/response.t
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,55 @@ done
aaa:
--- no_error_log
[error]



=== TEST 8: hold_body_chunk (ngx.arg[2] == true and ngx.arg[1] ~= "")
--- config
location = /t {
content_by_lua_block {
-- Nginx uses a separate buf to mark the end of the stream,
-- hence when ngx.arg[2] == true, ngx.arg[1] will be equal to "".
-- To avoid something unexpected, here we add a test to verify
-- this situation via mock.
local t = ngx.arg
local metatable = getmetatable(t)
local count = 0
setmetatable(t, {__index = function(t, idx)
if count == 0 then
if idx == 1 then
return "hello "
end
count = count + 1
return false
end
if count == 1 then
if idx == 1 then
return "world\n"
end
count = count + 1
return true
end
return metatable.__index(t, idx)
end,
__newindex = metatable.__newindex})
-- trigger body_filter_by_lua_block
ngx.print("A")
}
body_filter_by_lua_block {
local core = require("apisix.core")
local final_body = core.response.hold_body_chunk(ngx.ctx)
if not final_body then
return
end
ngx.arg[1] = final_body
}
}
--- request
GET /t
--- response_body
hello world
--- no_error_log
[error]

0 comments on commit c25e112

Please sign in to comment.