Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Internal refactoring to remove internal RequestData and rename internal Request to ClientRequestStream #481

Merged
merged 2 commits into from
Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace React\Http\Client;

use Psr\Http\Message\RequestInterface;
use React\EventLoop\LoopInterface;
use React\Socket\ConnectorInterface;
use React\Http\Io\ClientRequestStream;
use React\Socket\Connector;
use React\Socket\ConnectorInterface;

/**
* @internal
Expand All @@ -22,10 +24,9 @@ public function __construct(LoopInterface $loop, ConnectorInterface $connector =
$this->connector = $connector;
}

public function request($method, $url, array $headers = array(), $protocolVersion = '1.0')
/** @return ClientRequestStream */
public function request(RequestInterface $request)
{
$requestData = new RequestData($method, $url, $headers, $protocolVersion);

return new Request($this->connector, $requestData);
return new ClientRequestStream($this->connector, $request);
}
}
127 changes: 0 additions & 127 deletions src/Client/RequestData.php

This file was deleted.

44 changes: 31 additions & 13 deletions src/Client/Request.php → src/Io/ClientRequestStream.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

namespace React\Http\Client;
namespace React\Http\Io;

use Evenement\EventEmitter;
use Psr\Http\Message\RequestInterface;
use React\Promise;
use React\Socket\ConnectionInterface;
use React\Socket\ConnectorInterface;
Expand All @@ -16,28 +17,33 @@
* @event end
* @internal
*/
class Request extends EventEmitter implements WritableStreamInterface
class ClientRequestStream extends EventEmitter implements WritableStreamInterface
{
const STATE_INIT = 0;
const STATE_WRITING_HEAD = 1;
const STATE_HEAD_WRITTEN = 2;
const STATE_END = 3;

/** @var ConnectorInterface */
private $connector;
private $requestData;

/** @var RequestInterface */
private $request;

/** @var ?ConnectionInterface */
private $stream;

private $buffer;
private $responseFactory;
private $state = self::STATE_INIT;
private $ended = false;

private $pendingWrites = '';

public function __construct(ConnectorInterface $connector, RequestData $requestData)
public function __construct(ConnectorInterface $connector, RequestInterface $request)
{
$this->connector = $connector;
$this->requestData = $requestData;
$this->request = $request;
}

public function isWritable()
Expand All @@ -49,28 +55,36 @@ private function writeHead()
{
$this->state = self::STATE_WRITING_HEAD;

$requestData = $this->requestData;
$request = $this->request;
$streamRef = &$this->stream;
$stateRef = &$this->state;
$pendingWrites = &$this->pendingWrites;
$that = $this;

$promise = $this->connect();
$promise->then(
function (ConnectionInterface $stream) use ($requestData, &$streamRef, &$stateRef, &$pendingWrites, $that) {
function (ConnectionInterface $stream) use ($request, &$streamRef, &$stateRef, &$pendingWrites, $that) {
$streamRef = $stream;
assert($streamRef instanceof ConnectionInterface);

$stream->on('drain', array($that, 'handleDrain'));
$stream->on('data', array($that, 'handleData'));
$stream->on('end', array($that, 'handleEnd'));
$stream->on('error', array($that, 'handleError'));
$stream->on('close', array($that, 'handleClose'));

$headers = (string) $requestData;
assert($request instanceof RequestInterface);
$headers = "{$request->getMethod()} {$request->getRequestTarget()} HTTP/{$request->getProtocolVersion()}\r\n";
foreach ($request->getHeaders() as $name => $values) {
foreach ($values as $value) {
$headers .= "$name: $value\r\n";
}
}

$more = $stream->write($headers . $pendingWrites);
$more = $stream->write($headers . "\r\n" . $pendingWrites);

$stateRef = Request::STATE_HEAD_WRITTEN;
assert($stateRef === ClientRequestStream::STATE_WRITING_HEAD);
$stateRef = ClientRequestStream::STATE_HEAD_WRITTEN;

// clear pending writes if non-empty
if ($pendingWrites !== '') {
Expand Down Expand Up @@ -217,20 +231,24 @@ public function close()

protected function connect()
{
$scheme = $this->requestData->getScheme();
$scheme = $this->request->getUri()->getScheme();
if ($scheme !== 'https' && $scheme !== 'http') {
return Promise\reject(
new \InvalidArgumentException('Invalid request URL given')
);
}

$host = $this->requestData->getHost();
$port = $this->requestData->getPort();
$host = $this->request->getUri()->getHost();
$port = $this->request->getUri()->getPort();

if ($scheme === 'https') {
$host = 'tls://' . $host;
}

if ($port === null) {
$port = $scheme === 'https' ? 443 : 80;
}

return $this->connector
->connect($host . ':' . $port);
}
Expand Down
16 changes: 12 additions & 4 deletions src/Io/Sender.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ public function __construct(HttpClient $http)
*/
public function send(RequestInterface $request)
{
// support HTTP/1.1 and HTTP/1.0 only, ensured by `Browser` already
assert(\in_array($request->getProtocolVersion(), array('1.0', '1.1'), true));

$body = $request->getBody();
$size = $body->getSize();

Expand All @@ -91,12 +94,17 @@ public function send(RequestInterface $request)
$size = 0;
}

$headers = array();
foreach ($request->getHeaders() as $name => $values) {
$headers[$name] = implode(', ', $values);
// automatically add `Connection: close` request header for HTTP/1.1 requests to avoid connection reuse
if ($request->getProtocolVersion() === '1.1' && !$request->hasHeader('Connection')) {
$request = $request->withHeader('Connection', 'close');
}

// automatically add `Authorization: Basic …` request header if URL includes `user:pass@host`
if ($request->getUri()->getUserInfo() !== '' && !$request->hasHeader('Authorization')) {
$request = $request->withHeader('Authorization', 'Basic ' . \base64_encode($request->getUri()->getUserInfo()));
}

$requestStream = $this->http->request($request->getMethod(), (string)$request->getUri(), $headers, $request->getProtocolVersion());
$requestStream = $this->http->request($request);

$deferred = new Deferred(function ($_, $reject) use ($requestStream) {
// close request stream if request is cancelled
Expand Down
13 changes: 7 additions & 6 deletions tests/Client/FunctionalIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\Loop;
use React\Http\Client\Client;
use React\Http\Message\Request;
use React\Promise\Deferred;
use React\Promise\Stream;
use React\Socket\ConnectionInterface;
Expand Down Expand Up @@ -45,7 +46,7 @@ public function testRequestToLocalhostEmitsSingleRemoteConnection()
$port = parse_url($socket->getAddress(), PHP_URL_PORT);

$client = new Client(Loop::get());
$request = $client->request('GET', 'http://localhost:' . $port);
$request = $client->request(new Request('GET', 'http://localhost:' . $port, array(), '', '1.0'));

$promise = Stream\first($request, 'close');
$request->end();
Expand All @@ -62,7 +63,7 @@ public function testRequestLegacyHttpServerWithOnlyLineFeedReturnsSuccessfulResp
});

$client = new Client(Loop::get());
$request = $client->request('GET', str_replace('tcp:', 'http:', $socket->getAddress()));
$request = $client->request(new Request('GET', str_replace('tcp:', 'http:', $socket->getAddress()), array(), '', '1.0'));

$once = $this->expectCallableOnceWith('body');
$request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($once) {
Expand All @@ -83,7 +84,7 @@ public function testSuccessfulResponseEmitsEnd()

$client = new Client(Loop::get());

$request = $client->request('GET', 'http://www.google.com/');
$request = $client->request(new Request('GET', 'http://www.google.com/', array(), '', '1.0'));

$once = $this->expectCallableOnce();
$request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($once) {
Expand All @@ -109,7 +110,7 @@ public function testPostDataReturnsData()
$client = new Client(Loop::get());

$data = str_repeat('.', 33000);
$request = $client->request('POST', 'https://' . (mt_rand(0, 1) === 0 ? 'eu.' : '') . 'httpbin.org/post', array('Content-Length' => strlen($data)));
$request = $client->request(new Request('POST', 'https://' . (mt_rand(0, 1) === 0 ? 'eu.' : '') . 'httpbin.org/post', array('Content-Length' => strlen($data)), '', '1.0'));

$deferred = new Deferred();
$request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($deferred) {
Expand Down Expand Up @@ -141,7 +142,7 @@ public function testPostJsonReturnsData()
$client = new Client(Loop::get());

$data = json_encode(array('numbers' => range(1, 50)));
$request = $client->request('POST', 'https://httpbin.org/post', array('Content-Length' => strlen($data), 'Content-Type' => 'application/json'));
$request = $client->request(new Request('POST', 'https://httpbin.org/post', array('Content-Length' => strlen($data), 'Content-Type' => 'application/json'), '', '1.0'));

$deferred = new Deferred();
$request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($deferred) {
Expand Down Expand Up @@ -170,7 +171,7 @@ public function testCancelPendingConnectionEmitsClose()

$client = new Client(Loop::get());

$request = $client->request('GET', 'http://www.google.com/');
$request = $client->request(new Request('GET', 'http://www.google.com/', array(), '', '1.0'));
$request->on('error', $this->expectCallableNever());
$request->on('close', $this->expectCallableOnce());
$request->end();
Expand Down
Loading