swoole / swoole-src

🚀 Coroutine-based concurrency library for PHP
https://www.swoole.com
Apache License 2.0
18.43k stars 3.16k forks source link

Feature request: response lifecycle events #1825

Open sshymko opened 6 years ago

sshymko commented 6 years ago

There's a number of use cases that require tracking response lifecycle: before/after sending headers, before/after sending response body to a client. It would be great to be able to subscribe custom handlers for all such events.

For example:

$server->on('request', function($request, $response) {
    // Add default headers
    $response->on('headers_send_before', function ($response) {
        if (empty($response->header['Content-Type'])) {
            $response->header('Content-Type', 'text/html');
        }
    });
    // Business logic...
});

Another good use case is profiling, for example, via Blackfire. The profiler needs to start at the very beginning of the request handling (already supported) and stop right before sending out response headers to be able to report results in custom headers. See upscalesoftware/swoole-blackfire.

For example:

$profiler = new \Upscale\Swoole\Blackfire\Profiler();

$server->on('request', function($request, $response) use ($profiler) {
    $profiler->start($request);
    $response->on('headers_send_before', function ($response) use ($request, $profiler) {
        $profiler->stop($request, $response);
    });
    // Business logic subject to profiling...
});

The profiler above would work regardless of how the business logic prepares the response. Otherwise, the profiler stop call needs to be carefully placed right before the business logic sends the response. It's unnecessary burden for a developer to strategically place the stop call in different places for each application intended to be profiled. Moreover, a poorly-designed application may not even have a single place of the response preparation. Such apps still need to be profiled somehow :)

ghost commented 6 years ago

+1 for those handlers

twose commented 6 years ago

wait, if you have not used the write method, all data(included header) will be sent after you call end.

ghost commented 6 years ago

twose is ok - for me i did not found any real usecase last weeks

sshymko commented 5 years ago

@flddr and @twose Transparent profiling of an application regardless of the response population workflow is the use case. Library upscalesoftware/swoole-blackfire introduces the response proxy with the event subscription. There is no way to stop the profiling and append the response headers with the profiling results before the body is sent by an application being profiled without modifying the application itself.