lua-nginx-module
lua-nginx-module copied to clipboard
feature: implement keepalive socket context
A new option is added to the tcp.connect options_table:
ctx = boolean, where a "true" value would change the value returned from connect from current ok, err to:
local socket_ctx, reused = sock:connect('127.0.0.1', 5432, {ctx = true})
if not socket_ctx then
return nil, reused
end
if reused == 0 then
setmetatable(socket_ctx, some_mt)
end
socket_ctx.sock = sock
socket_ctx:execute("select $1, $2", 1, 2)
if reused < 100 then
sock:setkeepalive()
end
I hereby granted the copyright of the changes in this pull request to the authors of this lua-nginx-module project.
this is the basic idea for usage:
local pg = {
login = function() return true end,
prepare = function(self, query)
local portal = (self.nportals or 0) + 1
local ok, err = ngx.say("prepare ", portal, " ", query)
if not ok then
return nil, err
end
self.nportals, self[query] = portal, portal
return portal
end,
execute = function(self, query, ...)
if not query then
return nil, "no query defined"
end
local portal, err = self[query]
if not portal then
portal, err = self:prepare(query)
if not portal then
return nil, err
end
end
ngx.say("execute ", portal, " ", table.concat({...}, ", "))
end
}
local pg_mt = { __index = pg }
local conn_opts = { ctx = true }
return {
go = function()
local query = ngx.unescape_uri(ngx.var.arg_query)
if not query then
return nil, "query must be spesified"
end
local sock = ngx.socket.tcp()
local sock_ctx, reused = sock:connect('127.0.0.1', 1234, conn_opts)
if not sock_ctx then
return nil, reused
end
if reused == 0 then
setmetatable(sock_ctx, pg_mt)
if not sock_ctx:login() then
return nil, "login failed"
end
end
sock_ctx.sock = sock
sock_ctx:execute(query, reused, sock_ctx.nportals)
sock:setkeepalive()
end
}
Three questions:
- I am not sure if it's a good idea to change the return values from
ok, err
toctx, reused|err
. - Maybe we need a new API to create ctx on demand, just like
ngx.ctx
. - More test cases, please.
@thibaultcha, what is your opinion?
This pull request is now in conflict :(