From 45563486589eef67755e2c69ad32544c014098e1 Mon Sep 17 00:00:00 2001 From: Sangdeuk Kwon Date: Thu, 5 Jun 2025 10:56:13 +0900 Subject: [PATCH] bugfix: Semaphore not cleaned up on request timeout After a ngx.semaphore.wait() call, if the current request is terminated by Nginx due to client_header_timeout or client_body_timeout, the corresponding post() is never executed. As a result, all subsequent attempts to wait() on the same semaphore hang until they time out, because the semaphore count was never restored. https://github.com/openresty/lua-nginx-module/issues/2422 --- lib/ngx/semaphore.lua | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/lib/ngx/semaphore.lua b/lib/ngx/semaphore.lua index 58293c5e4..3e034b21a 100644 --- a/lib/ngx/semaphore.lua +++ b/lib/ngx/semaphore.lua @@ -45,7 +45,8 @@ if subsystem == 'http' then int ngx_http_lua_ffi_sema_new(ngx_http_lua_sema_t **psem, int n, char **errmsg); - int ngx_http_lua_ffi_sema_post(ngx_http_lua_sema_t *sem, int n); + int ngx_http_lua_ffi_sema_post(ngx_http_request_t *r, + ngx_http_lua_sema_t *sem, int n); int ngx_http_lua_ffi_sema_count(ngx_http_lua_sema_t *sem); @@ -72,7 +73,8 @@ elseif subsystem == 'stream' then int ngx_stream_lua_ffi_sema_new(ngx_stream_lua_sema_t **psem, int n, char **errmsg); - int ngx_stream_lua_ffi_sema_post(ngx_stream_lua_sema_t *sem, int n); + int ngx_stream_lua_ffi_sema_post(ngx_stream_lua_request_t *r, + ngx_stream_lua_sema_t *sem, int n); int ngx_stream_lua_ffi_sema_count(ngx_stream_lua_sema_t *sem); @@ -167,6 +169,11 @@ function _M.post(self, n) error("not a semaphore instance", 2) end + local r = get_request() + if not r then + error("no request found") + end + local cdata_sem = self.sem local num = n and tonumber(n) or 1 @@ -175,7 +182,7 @@ function _M.post(self, n) end -- always return NGX_OK - ngx_lua_ffi_sema_post(cdata_sem, num) + ngx_lua_ffi_sema_post(r, cdata_sem, num) return true end