Skip to content

Commit

Permalink
Store if an H2 connection was made
Browse files Browse the repository at this point in the history
If a prior HTTPS connection returned a non-H2 connection, the pool assumes the next connection will also not be H2.

Related to #246.
  • Loading branch information
trowski committed Jan 9, 2020
1 parent 1181944 commit 6bb79ba
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/Connection/UnlimitedConnectionPool.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ final class UnlimitedConnectionPool implements ConnectionPool
/** @var Promise[][] */
private $connections = [];

/** @var bool[] */
private $waitForPriorConnection = [];

/** @var int */
private $totalConnectionAttempts = 0;

Expand Down Expand Up @@ -76,15 +79,15 @@ public function getStream(Request $request, CancellationToken $cancellation): Pr
}

$authority = $host . ':' . $port;
$key = $scheme . '://' . $authority;
$uri = $scheme . '://' . $authority;

$connections = $this->connections[$key] ?? new \ArrayObject;
$connections = $this->connections[$uri] ?? new \ArrayObject;

foreach ($connections as $connectionPromise) {
\assert($connectionPromise instanceof Promise);

try {
if ($isHttps) {
if ($isHttps && ($this->waitForPriorConnection[$uri] ?? true)) {
// Wait for first successful connection if using a secure connection (maybe we can use HTTP/2).
$connection = yield $connectionPromise;
} else {
Expand Down Expand Up @@ -117,23 +120,27 @@ public function getStream(Request $request, CancellationToken $cancellation): Pr
$connectionPromise = $this->connectionFactory->create($request, $cancellation);

$hash = \spl_object_hash($connectionPromise);
$this->connections[$key] = $this->connections[$key] ?? new \ArrayObject;
$this->connections[$key][$hash] = $connectionPromise;
$this->connections[$uri] = $this->connections[$uri] ?? new \ArrayObject;
$this->connections[$uri][$hash] = $connectionPromise;

try {
$connection = yield $connectionPromise;
$this->openConnectionCount++;

\assert($connection instanceof Connection);
} catch (\Throwable $exception) {
$this->dropConnection($key, $hash);
$this->dropConnection($uri, $hash);

throw $exception;
}

$connection->onClose(function () use ($key, $hash): void {
if ($isHttps) {
$this->waitForPriorConnection[$uri] = \in_array('2', $connection->getProtocolVersions());
}

$connection->onClose(function () use ($uri, $hash): void {
$this->openConnectionCount--;
$this->dropConnection($key, $hash);
$this->dropConnection($uri, $hash);
});

$stream = yield $connection->getStream($request);
Expand All @@ -150,6 +157,7 @@ private function dropConnection(string $uri, string $connectionHash): void

if (empty($this->connections[$uri])) {
unset($this->connections[$uri]);
unset($this->waitForPriorConnection[$uri]);
}
}
}

0 comments on commit 6bb79ba

Please sign in to comment.