lua-nginx-module icon indicating copy to clipboard operation
lua-nginx-module copied to clipboard

[discuss]: support use native Lua coroutine in `init_worker` phase

Open tzssangglass opened this issue 5 months ago • 3 comments

According to the documentation here: https://github.com/openresty/lua-nginx-module#coroutinecreate

coroutine.create can be used in init_by_lua*, header_filter_by_lua*, body_filter_by_lua*, because OpenResty would replace OpenResty's coroutine with the Lua native coroutine in these phases, which can not yield.

code: https://github.com/openresty/lua-nginx-module/blob/d34d3c545e80bccbd8110235d73474c11895bd2e/src/ngx_http_lua_coroutine.c#L336-L375

And also here: https://github.com/openresty/lua-resty-core/blob/master/lib/resty/core/coroutine.lua#L4-L24

Now the problem is: If I call coroutine.create in init_worker phase, match the

                if ctx ~= 0x020 and ctx ~= 0x040 then
                    return ours(...)
                end

And then return the OpenResty's coroutine. (ctx of init_worker is 0x0100)

This would cause ean rror API disabled in the context of init_worker_by_lua* because check here: https://github.com/openresty/lua-nginx-module/blob/d34d3c545e80bccbd8110235d73474c11895bd2e/src/ngx_http_lua_coroutine.c#L117

So I suggest returning the Lua native coroutine in the init_worker phase, change like

                if ctx ~= 0x020 and ctx ~= 0x040 and ctx ~= 0x0100 then
                    return ours(...)
                end

This may allow users to use native Lua coroutine in init_worker phase.

tzssangglass avatar Jul 23 '25 18:07 tzssangglass

ping @zhuizhuhaomeng

tzssangglass avatar Jul 24 '25 02:07 tzssangglass

FYI, we have the cosocket impl PR in the init_worker phase before https://github.com/openresty/lua-nginx-module/pull/1825

oowl avatar Aug 09 '25 17:08 oowl

In this case, we don't need a cosocket in the init_worker phase; instead, we allow users to use native Lua coroutines in this phase.

tzssangglass avatar Aug 22 '25 06:08 tzssangglass