How can a content handler block on certain events before sending a response?

Maxim Dounin mdounin at mdounin.ru
Tue Nov 23 03:48:45 MSK 2010


Hello!

On Tue, Nov 23, 2010 at 12:34:31AM +0100, Hongli Lai wrote:

> I'm writing an Nginx module and I'd like to better understand how Nginx
> content handlers work and how the Nginx main loop works.
> 
> As far as I know, Nginx content handler functions are supposed to create
> a chain link of buffers containing the response data, and then call
> ngx_http_output_filter(r, &the_chain_link) which will then take care of
> passing this data to the next output filter and eventually sending the
> data to the HTTP client.
> 
> How does one deal with situations in which the content handler function
> cannot immediately generate a response? For example, suppose my content
> handler must first fetch some data from MySQL. Since Nginx is an evented
> server, I imagine that I need to do something like this:
> 1. Connect to MySQL and send a request to it.
> 2. Register the MySQL client file descriptor on the Nginx main loop.
> 3. The Nginx main loop notifies me when the MySQL fd becomes readable.
> 4. I read the MySQL response, generate HTTP response data, and call
> ngx_http_output_filter().
> 
> But how do I do step 2? Which function do I need to call? What should I
> return in my content handler function after having executed step 2?
> NGX_AGAIN?

>From content handler you should return NGX_DONE to indicate you 
are going to send response later.  Note that after returing NGX_DONE 
you are responsible for finalizing request as well, this should be 
done via ngx_http_finalize_request() call.

For an idea how to handle connection, data sending and receiving 
please follow upstream module (src/http/ngx_http_upstream.c) and 
handlers which use it (e.g. memcached module, 
src/http/modules/ngx_http_memcached_module.c).

Working with events isn't something trivial, but basically you'll 
have to connect via ngx_event_connect_peer(), set up appropriate 
read/write handlers in resulting connection structure and call 
ngx_handle_(read|write)_event() as appropriate.

Maxim Dounin



More information about the nginx mailing list