http-client: Cannot multiplex requests on a single H2 connection

Spotted at https://github.com/symfony/symfony/pull/35115#issuecomment-572057741

The following script adapted from the examples doesn’t multiplex the requests. Note that we limit to one single connection. If we remove this limit, one connection per request is made and all works concurrently - but then this is no different than using HTTP/1.1.

<?php

use Amp\Http\Client\Connection\LimitedConnectionPool;
use Amp\Http\Client\Connection\UnlimitedConnectionPool;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Amp\Loop;
use Amp\Sync\LocalKeyedSemaphore;

require __DIR__ . '/vendor/autoload.php';

Loop::run(static function () use ($argv) {
    $uris = [];

    for ($i = 0; $i < 379; ++$i) {
        $uris[] = "https://http2.akamai.com/demo/tile-$i.png";
    }

    // Instantiate the HTTP client
    $pool = LimitedConnectionPool::byHost(new UnlimitedConnectionPool, new LocalKeyedSemaphore(1));
    $client = (new HttpClientBuilder)
            ->usingPool($pool)
            ->build();

    $requestHandler = static function (string $uri) use ($client) {
        /** @var Response $response */
        $response = yield $client->request(new Request($uri));

        return yield $response->getBody()->buffer();
    };

    try {
        $promises = [];

        foreach ($uris as $uri) {
            $promises[$uri] = Amp\call($requestHandler, $uri);
        }

        $bodies = yield $promises;

        foreach ($bodies as $uri => $body) {
            print $uri . " - " . \strlen($body) . " bytes" . PHP_EOL;
        }
    } catch (HttpException $error) {
        // If something goes wrong Amp will throw the exception where the promise was yielded.
        // The HttpClient::request() method itself will never throw directly, but returns a promise.
        echo $error;
    }
});

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 19 (19 by maintainers)

Commits related to this issue

Most upvoted comments

Yup, please.