Skip to content

Commit

Permalink
Wait to close socket until last stream released
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Nov 28, 2024
1 parent f982102 commit 4e391ab
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/Connection/Internal/Http2ConnectionProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ final class Http2ConnectionProcessor implements Http2Processor

private ?int $shutdown = null;

private ?int $lastStream = null;

private readonly Queue $frameQueue;

public function __construct(
Expand Down Expand Up @@ -1380,6 +1382,10 @@ private function releaseStream(int $streamId, ?\Throwable $exception, bool $unpr
}
}

if ($this->shutdown !== null && $streamId === $this->lastStream) {
$this->socket->close();
}

if (!$this->streams && !$this->socket->isClosed() && $this->socket instanceof ResourceStream) {
$this->socket->unreference();
}
Expand Down Expand Up @@ -1444,6 +1450,9 @@ private function shutdown(?HttpException $reason = null, ?int $lastId = null): v

$code = $previous?->getCode() ?? Http2Parser::GRACEFUL_SHUTDOWN;

$this->shutdown = $code;
$this->lastStream = $lastId ?? $this->streamId;

if ($lastId === null) {
$message = match ($code) {
Http2Parser::PROTOCOL_ERROR,
Expand All @@ -1455,24 +1464,22 @@ private function shutdown(?HttpException $reason = null, ?int $lastId = null): v
default => null,
};

$this->writeFrame(Http2Parser::GOAWAY, data: \pack('N', $code) . $message)
->finally($this->socket->close(...))
->ignore();
$this->writeFrame(Http2Parser::GOAWAY, data: \pack('NN', 0, $code) . $message)->ignore();

foreach ($this->streams as $id => $stream) {
$this->releaseStream($id, $reason, unprocessed: false);
}
} else {
foreach ($this->streams as $id => $stream) {
if ($id <= $lastId) {
continue;
}

$this->releaseStream($id, $reason, unprocessed: true);
}
return;
}

$this->shutdown = $code;
foreach ($this->streams as $id => $stream) {
if ($id <= $lastId) {
continue;
}

$this->releaseStream($id, $reason, unprocessed: true);
}
}

/**
Expand Down

0 comments on commit 4e391ab

Please sign in to comment.