简体   繁体   中英

How to get a connection abort event from client side in an aws-lambda function that runs php script?

I am successfully running php code on an aws-lambda function which is initialized by an aws api gateway and runs on nodejs run time.
I want to capture how much time a client spent on my page.
The time capture logic is working fine on my server but I can't get it to run on aws-lambda .
Please, can any one help me out? How can I get a client disconnect notification in my php code ?

The following code was used to get a connection abort in php :

ignore_user_abort( true );

while ( 1 )
        {
            ob_flush();
            flush();
            echo "1";

            if ( connection_aborted() )
            {
                Log::info('connection aborted detected');
                $end_time1 = microtime( true );
                break;
            }
            else
            {
                $end_time1 = microtime( true );
                $second = $end_time1 - $start_time;
                if ( $second >= 25 )
                {
                    break;
                }
            }
            // Sleep
            usleep( 300000 );
        }

Assume that all php variables are set with appropriate values.
I just can't get the if condition if ( connection_aborted() ) to be true when the client closes the connection by either closing browser or any another way.

Or is there any way to know that the API gateway disconnected from client side?

Note: the above code is working fine in my local server as well as on the stage server, but it's not working on the aws-lambda function.

This is not something Lambda can do, because the condition is impossible to detect inside the Lambda runtime environment due to the decoupling built in to Lambda.

When a Lambda function is invoked, the client (browser) isn't actually connected to the container running the function. It's connected to the Lambda service which has used a separate connection to the container, to invoke the function.

If the client closes the connection, the function still runs to completion but the response is discarded by the service, since there is nobody to return it to.

flush() and ob_flush() are almost certainly no-ops, because Lambda is strictly request/response. The entire response is returned when execution is complete -- nothing is returned prior to that, so there is nothing to flush while the function is still executing.

If this is a really important capability, consider using API Gateway Web Sockets , which fire Lambda functions when connections are opened and again when closed. It's an unusual use case for that feature, but it would avoid the expense of long-running Lambda functions (which can't be used, anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM