amphp / http-server

An advanced async HTTP server library for PHP, perfect for real-time apps and APIs with high concurrency demands.
https://amphp.org/http-server
MIT License
1.29k stars 101 forks source link

How to specify timeout for SocketHttpServer. #371

Open LacticWhale opened 1 month ago

LacticWhale commented 1 month ago

Problem: I need to create api and some methods I call can take up to 45 seconds to generate a response. Is there a way to remove or increase timeout.

I copied example with delayed response and increased wait time to 30 seconds.

#!/usr/bin/env php
<?php declare(strict_types=1);

require "vendor/autoload.php";

use Amp\ByteStream;
use Amp\Http\HttpStatus;
use Amp\Http\Server\DefaultErrorHandler;
use Amp\Http\Server\Request;
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\SocketHttpServer;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\PsrLogMessageProcessor;
use function Amp\delay;
use function Amp\trapSignal;

// Run this script, then visit http://localhost:1338/ in your browser.

$logHandler = new StreamHandler(ByteStream\getStdout());
$logHandler->pushProcessor(new PsrLogMessageProcessor());
$logHandler->setFormatter(new ConsoleFormatter());
$logger = new Logger('server');
$logger->pushHandler($logHandler);

$server = SocketHttpServer::createForDirectAccess($logger);

$server->expose("0.0.0.0:1338");
$server->expose("[::]:1338");

$server->start(new ClosureRequestHandler(function (Request $request) use($logger): Response {
    // We delay the response here, but this could also be non-blocking I/O.
    // Further requests are still processed concurrently.
    delay(30);

    $logger->info("End of delay.");

    return new Response(HttpStatus::OK, [
        "content-type" => "text/plain; charset=utf-8",
    ], "Hello, World!");
}), new DefaultErrorHandler());

// Await a termination signal to be received.
$signal = trapSignal([\SIGHUP, \SIGINT, \SIGQUIT, \SIGTERM]);

$logger->info(sprintf("Received signal %d, stopping HTTP server", $signal));

$server->stop();

And result I get:

$ time curl -m 60 http://127.0.0.1:1338/
curl: (52) Empty reply from server

real    0m14.483s
user    0m0.009s
sys     0m0.006s
Brissan2025 commented 1 month ago

I also encountered this problem, please advise the solution to this issue

kelunik commented 1 month ago

It seems like the timeout is implemented improperly here. It should only apply while the client is still sending data.