Hello!
On Mon, Aug 11, 2014 at 2:20 AM, Jerome Lafon wrote:
> So if I understand well a good way to manage running queries would be to let
> them finish and after that to put the connection in the connection pool
> right?
Yes.
> For doing that I could use a field like ngx.ctx.pgsql_running to mark the
> begining and the end of each query and in ngx.on_abort I would have to check
> the flag ngx.ctx.pgsql_running: If a query is running I am doing a loop with
> a ngx.sleep(0.1) until the end of the query. At the end I put the connection
> in the connection pool and I can call ngx.exit().
No. Use of ngx.sleep() in your ngx.on_abort handler is sub-optimal.
Active ngx.sleep() has some extra overhead, your running ngx.on_abort
"light thread" has some extra overhead, and your sleeping may
introduce extra delay than needed, which is also a waste of resources.
A better approach is to define two Lua functions to guard every call
of your Pg operations:
enter_critical()
-- your Pg query
leave_critical()
And you maintain a reference count in ngx.ctx, say, ngx.ctx.crit_cnt,
to keep track of the number of active "critical sections" in effect.
So in enter_critical(), you increment the counter, while in
leave_critical(), you decrement it.
Further, in your ngx.on_abort() handler, you check the counter, if
it's 0, then you call ngx.exit(444) right away; otherwise, you set a
flag in ngx.ctx, say, ngx.ctx.die, to true, and then your
ngx.on_abort() handler just silently returns right away *without
waiting*.
Finally, in your leave_critical() function, after decrementing the
counter, it checks if the counter is zero -- if yes, you check this
ngx.ctx.die flag; if true, call ngx.exit(444) (on the behalf of your
ngx.on_abort handler, which already quits at that point).
> For managing the field ngx.ctx.pgsql_running I have to modify the lib
> resty.postgres directly right?
>
No. Just put the guards (see above) around your Pg calls (and possibly
other things worth protecting).
Regards,
-agentzh